简体   繁体   English

如何使用循环将列表的项目附加到另一个列表

[英]How to append items of a list to another list using a loop

Having two lists:有两个列表:

list1 = ['Me','You','Sam']
list2 = ['Joe','Jen']

How can I append items of list2 to the list1 ?如何将list2项目附加到list1 Expected result is:预期结果是:

['Me', 'You','Sam','Joe','Jen']

My failed attempt:我失败的尝试:

list1 = ("Bobs","Sams","Jacks"); 
foreach list2 in list1:
    list3 = list2 + " list item"

print list3

This should get you started:这应该让你开始:

list1 = ['Me','You','Sam']
list2 = ['Joe','Jen']

for item in list2:
   list1.append(item)

list1 now is ['Me', 'You','Sam','Joe','Jen'] list1 现在是['Me', 'You','Sam','Joe','Jen']

If you want a third list, simply define it and append to it instead.如果你想要第三个列表,只需定义它并附加到它。

So a couple of things are wrong with your code.所以你的代码有一些问题。

First :第一

list = ("Bobs", "Sams", "Jacks"); should be list = ["Bobs", "Sams", "Jacks"]应该是list = ["Bobs", "Sams", "Jacks"]

Second :第二

foreach list2 in list1:
    list3 = list2 + " list item"

should be应该

list3 = []
for item in list1:
   list3.append(item)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM