[英]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.