如何使用循环Python建立清单 [英] How to build a list using a loop python

查看:93
本文介绍了如何使用循环Python建立清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python循环中获取项目以建立列表.在php中,我将使用以下内容:

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);

产生

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

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

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

在Python中,我尝试过:

In Python i tried:

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

print list3

产生

Jacks list item

但是它不会返回list3作为列表,并且list3[]无法正常工作.如何让循环进入列表?

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?

推荐答案

这应该使您入门:

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

for item in list2:
   list1.append(item)

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

如果要第三个列表,只需定义它,然后附加到它.

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

这篇关于如何使用循环Python建立清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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