簡體   English   中英

Python枚舉列表設置開始索引但不增加結束計數

[英]Python enumerate list setting start index but without increasing end count

我想遍歷一個列表,計數器從零開始,但列表的起始索引為 1,例如:

valueList = [1, 2, 3, 4]
secondList = ['a', 'b', 'c', 'd']

for i, item in enumerate(valueList, start=1):
    print(secondList[i])

代碼因索引超出范圍錯誤而失敗(我意識到這是因為我以列表的長度 -1 加上起始值結束,並且 Python 列表的索引為零,因此以這種方式使用 i 來調用另一個中的第 i 個元素列表無效)。 下面的工作,但對 i 大於零的測試的添加看起來不是 Pythonic。

valueList = [1, 2, 3, 4]
secondList = ['a', 'b', 'c', 'd']

for i, item in enumerate(valueList, start=0):
    if i > 0:  
        print(secondList[i]) 

枚舉不是正確的選擇,還有其他方法嗎?

聽起來好像您想對列表進行切片 仍然從一開始enumerate()以獲得相同的索引:

for i, item in enumerate(valueList[1:], start=1):

然后從第二個元素開始循環遍歷valueList ,並使用匹配的索引:

>>> valueList = [1, 2, 3, 4]
>>> secondList = ['a', 'b', 'c', 'd']
>>> for i, item in enumerate(valueList[1:], start=1):
...     print(secondList[i])
... 
b
c
d

在這種情況下,我只使用zip()代替,也許結合itertools.islice()

from itertools import islice

for value, second in islice(zip(valueList, secondList), 1, None):
    print(value, second)

islice()調用會為您跳過第一個元素:

>>> from itertools import islice
>>> for value, second in islice(zip(valueList, secondList), 1, None):
...     print(value, second)
... 
2 b
3 c
4 d

問題不是枚舉,也不是start參數,而是當您執行start=1 ,您是從1枚舉到valueList+1的事實:

>>> valueList = [1, 2, 3, 4]
>>> secondList = ['a', 'b', 'c', 'd']
>>> for i, item in enumerate(valueList, start=1):
...     print(i)
...     print(secondList[i])
...     print('----')
... 
1
b
----
2
c
----
3
d
----
4
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range

所以當然,當您嘗試訪問secondList[4] ,沒有可用的值! 你可能想要這樣做:

>>> for i, item in enumerate(valueList, start=1):
...     if i < len(secondList):
...         print(secondList[i])
... 
b
c
d

也就是說,我不確定你到底想要達到什么目的。 如果您想跳過secondList的第一個值,這可能是一個解決方案,即使不是最有效的解決方案。 更好的方法是實際使用切片運算符:

>>> print(secondList[1:])
['b', 'c', 'd']

如果您想使用自然枚舉(而不是計算機的枚舉)迭代列表,即從1而不是0 ,那么這不是要走的路。 要顯示自然索引並使用計算機索引,您只需執行以下操作:

>>> for i, item in enumerate(valueList):
...     print("{} {}".format(i+1, secondList[i]))
... 
1 a
2 b
3 c
4 d

最后,您可以使用zip()而不是 enumerate 來鏈接兩個列表的內容:

>>> for i, item in zip(valueList, secondList):
...     print('{} {}'.format(i, item))
... 
1 a
2 b
3 c
4 d

這將顯示valueList每個值與相同索引處的secondList的值。

如果您的集合是生成器,您最好這樣做:

for i, item in enumerate(valueList, start=1):
    if i < 1:
        continue
    print(secondList[i])

或者修改 Martijn Pieters 的好答案,

from itertools import islice, izip
for value, second in islice(izip(valueList, secondList), 1, None):
    print(value, second)

這樣數據是延遲加載的。

或者不使用 start-parameter,你可以做一個 if-comparison i > 0。這樣你也不必在最后處理 list+1 索引錯誤:

for i, item in enumerate(valueList):
    if i > 0:
        continue
    print(secondList[i])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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