How to build a list using a loop python

♀尐吖头ヾ 提交于 2019-12-13 10:14:06

问题


How do I get items in a python loop to build a list. In php I would use something like this:

$ar1 = array("Bobs","Sams","Jacks"); 
foreach ($ar1 as $ar2){ 
$ar3[] = "$ar2 array item"; }

print_r($ar3);

which produces

Array ( [0] => Bobs array item [1] => Sams array item [2] => Jacks array item )

$ar3[] stores the item in the foreach in an array.

In Python i tried:

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

print list3

which produces

Jacks list item

But it doesn't return list3 as a list and list3[] doesn't work. how do I get the loop to feed into the list?


回答1:


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']

If you want a third list, simply define it and append to it instead.




回答2:


So a couple of things are wrong with your code.

First:

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

Second:

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

should be

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


来源:https://stackoverflow.com/questions/30381991/how-to-build-a-list-using-a-loop-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!