如何使用循环python构建列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30381991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:21:06  来源:igfitidea点击:

How to build a list using a loop python

pythonlistloopsstore

提问by user1721230

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

如何在 python 循环中获取项目以构建列表。在 php 中,我会使用这样的东西:

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

print_r($ar3);

which produces

产生

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

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

$ar3[]将 foreach 中的项存储在数组中。

In Python i tried:

在 Python 中,我尝试过:

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

print list3

which produces

产生

Hymans list item

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

但它不会list3作为列表返回并且list3[]不起作用。如何让循环输入列表?

采纳答案by datasci

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.

如果你想要第三个列表,只需定义它并附加到它。

回答by NendoTaka

So a couple of things are wrong with your code.

所以你的代码有一些问题。

First:

第一

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

list = ("Bobs", "Sams", "Hymans");应该 list = ["Bobs", "Sams", "Hymans"]

Second:

第二

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

should be

应该

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