如何将两个列表的元素添加到一个列表中? [英] How do i add two lists' elements into one list?

查看:669
本文介绍了如何将两个列表的元素添加到一个列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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通过组合您提供给它的可迭代对象中的元素来生成元组列表.因此,在您的情况下,它将返回从list1list2到最先耗尽的那对元素.

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.

这篇关于如何将两个列表的元素添加到一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆