Python:循环遍历列表项 x 次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14450966/
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
Python: loop through list item x times?
提问by michelle26
I am using Python2.7 and I would like to loop through a list x times.
我正在使用 Python2.7,我想循环遍历列表 x 次。
a=['string1','string2','string3','string4','string5']
for item in a:
print item
The above code will print all five items in the list, What if I just want to print the first 3 items? I searched over the internet but couldn't find an answer, it seems that xrange() will do the trick, but I can't figure out how.
上面的代码将打印列表中的所有五个项目,如果我只想打印前三个项目怎么办?我在互联网上搜索但找不到答案,似乎 xrange() 可以解决问题,但我不知道如何解决。
Thanks for your help!
谢谢你的帮助!
采纳答案by Abhijit
Sequence Slicingis what you are looking for. In this case, you need to slice the sequence to the first three elements to get them printed.
序列切片就是你要找的。在这种情况下,您需要将序列切片为前三个元素以打印它们。
a=['string1','string2','string3','string4','string5']
for item in a[:3]:
print item
Even, you don't need to loop over the sequence, just joinit with a newline and print it
甚至,你不需要遍历序列,只需用换行符加入它并打印它
print '\n'.join(a[:3])
回答by djjolicoeur
a=['string1','string2','string3','string4','string5']
for i in xrange(3):
print a[i]
回答by J. Katzwinkel
I think this would be considered pythonic:
我认为这将被视为pythonic:
for item in a[:3]:
print item
Edit: since a matter of seconds made this answer redundant, I will try to provide some background information:
编辑:由于几秒钟的时间使这个答案变得多余,我将尝试提供一些背景信息:
Array slicingallows for quick selection in sequences like Lists of Strings. A subsequence of a one-dimensional sequence can be specified by the indices of left and right endpoints:
数组切片允许在字符串列表等序列中快速选择。一维序列的子序列可以由左右端点的索引指定:
>>> [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]
Note that the left endpoint is included, the right one is not. You can add a third argument to select only every nth element of a sequence:
请注意,包括左端点,不包括右端点。您可以添加第三个参数以仅选择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]
By converting lists to numpyarrays, it is even possible to perform multi-dimensional slicing:
通过将列表转换为numpy数组,甚至可以执行多维切片:
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])

