如何将两个列表的元素添加到一个列表中?

编程入门 行业动态 更新时间:2024-10-22 17:26:49
本文介绍了如何将两个列表的元素添加到一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如,我有一个这样的列表:

For example, I have a list like this:

list1 = [good, bad, tall, big] list2 = [boy, girl, guy, man]

我想列出一个这样的列表:

and I want to make a list like this:

list3 = [goodboy, badgirl, tallguy, bigman]

我尝试了类似这样的事情:

I tried something like these:

list3=[] list3 = list1 + list2

,但这仅包含list1

所以我用了for:

list3 = [] for a in list1: for b in list2: c = a + b list3.append(c)

但是它会导致列表过多(在这种情况下,其中4 * 4 = 16个)

but it would result in too many lists(in this case, 4*4 = 16 of them)

我该怎么办?任何帮助都将非常棒!

What should i do? Any help would be really great!

推荐答案

您可以对zip使用列表推导:

You can use list comprehensions with zip:

list3 = [a + b for a, b in zip(list1, list2)]

zip通过组合您提供给它的可迭代对象中的元素来生成元组列表.因此,在您的情况下,它将返回从list1和list2到最先耗尽的那对元素.

zip produces a list of tuples by combining elements from iterables you give it. So in your case, it will return pairs of elements from list1 and list2, up to whichever is exhausted first.

更多推荐

如何将两个列表的元素添加到一个列表中?

本文发布于:2023-11-23 15:54:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   元素   两个   列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!