我想循环一个列表,计数器从零开始,但列表起始索引为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个另一个列表中的元素无效)。以下工作,但增加大于零的测试看起来是非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])
枚举不是正确的选择,还有另一种方式吗?
答案 0 :(得分:10)
听起来好像你想要切片列表;仍然在一个开始enumerate()
获得相同的索引:
for i, item in enumerate(valueList[1:], start=1):
然后从 second 元素开始循环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
答案 1 :(得分:1)
问题不是枚举,也不是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()
最后,您可以使用>>> for i, item in zip(valueList, secondList):
... print('{} {}'.format(i, item))
...
1 a
2 b
3 c
4 d
而不是枚举来链接两个列表的内容:
valueList
将在同一索引处显示secondList
的每个值附加{{1}}的值。
答案 2 :(得分:0)
如果您的收藏集是生成器,那么您最好这样做:
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)
通过这种方式延迟加载数据。