[英]Python: loop through list item x times?
我正在使用Python2.7,我想循环遍历列表x次。
a=['string1','string2','string3','string4','string5']
for item in a:
print item
上面的代码将打印列表中的所有五个项目,如果我只想打印前3个项目怎么办? 我在互联网上搜索但找不到答案,似乎xrange()会做到这一点,但我无法弄清楚如何。
谢谢你的帮助!
我认为这将被视为pythonic :
for item in a[:3]:
print item
编辑 :由于几秒钟的时间使这个答案变得多余,我将尝试提供一些背景信息:
数组切片允许在诸如字符串列表之类的序列中快速选择。 可以通过左端点和右端点的索引来指定一维序列的子序列:
>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]
请注意,包含左端点 ,右端不包含。 您可以添加第三个参数以仅选择序列的每个第n
个元素:
>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]
通过将列表转换为numpy数组,甚至可以执行多维切片:
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])
a=['string1','string2','string3','string4','string5']
for i in xrange(3):
print a[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.