簡體   English   中英

Python:遍歷列表項x次?

[英]Python: loop through list item x times?

我正在使用Python2.7,我想循環遍歷列表x次。

a=['string1','string2','string3','string4','string5']
for item in a:
  print item

上面的代碼將打印列表中的所有五個項目,如果我只想打印前3個項目怎么辦? 我在互聯網上搜索但找不到答案,似乎xrange()會做到這一點,但我無法弄清楚如何。

謝謝你的幫助!

序列切片是您正在尋找的。 在這種情況下,您需要將序列切片到前三個元素以打印它們。

a=['string1','string2','string3','string4','string5']
for item in a[:3]:
      print item

甚至,您不需要循環序列,只需其與換行符連接並打印即可

print '\n'.join(a[:3])

我認為這將被視為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM