我正在使用Python2.7,我想循環遍歷一個列表x次。Python:遍歷列表項x次?
a=['string1','string2','string3','string4','string5']
for item in a:
print item
上面的代碼將打印列表中的所有五個項目,如果我只想打印前3個項目,該怎麼辦?我在互聯網上搜索,但無法找到答案,似乎xrange()會做的伎倆,但我無法弄清楚如何。
感謝您的幫助!
我正在使用Python2.7,我想循環遍歷一個列表x次。Python:遍歷列表項x次?
a=['string1','string2','string3','string4','string5']
for item in a:
print item
上面的代碼將打印列表中的所有五個項目,如果我只想打印前3個項目,該怎麼辦?我在互聯網上搜索,但無法找到答案,似乎xrange()會做的伎倆,但我無法弄清楚如何。
感謝您的幫助!
Sequence Slicing是你在找什麼。在這種情況下,您需要將序列切片到前三個元素以打印它們。
a=['string1','string2','string3','string4','string5']
for item in a[:3]:
print item
即使,你並不需要遍歷序列,只是join它以新行並將其打印
print '\n'.join(a[:3])
a=['string1','string2','string3','string4','string5']
for i in xrange(3):
print a[i]
-1也迭代一個範圍,以便索引一個可迭代的 – wim
,我認爲這將被視爲Python的:
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]
注意,左endpoint is included,正確的是沒有的。可以添加第三個參數來選擇一個序列的僅每隔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','string6')] – michelle26
@ michelle26:'順序切片也可以用來切片元組列表...',這是一個任務嗎?離子或聲明? – Abhijit
如果你想加入它,你需要將這個列表弄平。 – wim