Python:遍历列表项x次?

mic*_*e26 7 python python-2.7

我正在使用Python2.7,我想循环遍历列表x次.

a=['string1','string2','string3','string4','string5']
for item in a:
  print item
Run Code Online (Sandbox Code Playgroud)

上面的代码将打印列表中的所有五个项目,如果我只想打印前3个项目怎么办?我在互联网上搜索但找不到答案,似乎xrange()会做到这一点,但我无法弄清楚如何.

谢谢你的帮助!

Abh*_*jit 19

序列切片是您正在寻找的.在这种情况下,您需要将序列切片到前三个元素以打印它们.

a=['string1','string2','string3','string4','string5']
for item in a[:3]:
      print item
Run Code Online (Sandbox Code Playgroud)

甚至,您不需要循环序列,只需其与换行符连接并打印即可

print '\n'.join(a[:3])
Run Code Online (Sandbox Code Playgroud)


J. *_*kel 6

我认为这将被视为pythonic:

for item in a[:3]:
    print item
Run Code Online (Sandbox Code Playgroud)

编辑:由于几秒钟的时间使这个答案变得多余,我将尝试提供一些背景信息:

数组切片允许在诸如字符串列表之类的序列中快速选择.可以通过左端点和右端点的索引来指定一维序列的子序列:

>>> [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]
Run Code Online (Sandbox Code Playgroud)

请注意,包含左端,右端不包含.您可以添加第三个参数以仅选择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]
Run Code Online (Sandbox Code Playgroud)

通过将列表转换为numpy数组,甚至可以执行多维切片:

>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
       [1, 3, 5]])
Run Code Online (Sandbox Code Playgroud)