可以访问索引/枚举的 Python 列表理解吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14864922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is Python list comprehension with access to the index/enumerate possible?
提问by Pav Ametvic
consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1:
考虑下面的 Python 代码,我用它在一个新的 list2 中添加了 list1 的索引从 1 到 3 的所有项目:
for ind, obj in enumerate(list1):
if 4> ind > 0: list2.append(obj)
how would you write this using python list comprehension, if I have no access to the indices through enumerate?
如果我无法通过枚举访问索引,您将如何使用 python 列表理解来编写它?
something like:
就像是:
list2 = [x for x in list1 if 4>ind>0]
but since I have no 'ind' number, would this work? :
但由于我没有“ind”号码,这行得通吗?:
list2 = [x for x in enumerate(list1) if 4>ind>0]
采纳答案by Pavel Anossov
list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
回答by BrenBarn
If you use enumerate, you dohave access to the index:
如果使用enumerate,则可以访问索引:
list2 = [x for ind, x in enumerate(list1) if 4>ind>0]
回答by John La Rooy
Unless your real use case is more complicated, you should just use a list slice as suggested by @wim
除非您的实际用例更复杂,否则您应该只使用@wim 建议的列表切片
>>> list1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']
>>> [x for ind, x in enumerate(list1) if 4 > ind > 0]
['one', 'two', 'three']
>>> list1[1:4]
['one', 'two', 'three']
For more complicated cases - if you don't actually need the index - it's clearer to iterate over a slice or an islice
对于更复杂的情况 - 如果您实际上不需要索引 - 迭代切片或 islice 会更清晰
list2 = [x*2 for x in list1[1:4]]
or
或者
from itertools import islice
list2 = [x*2 for x in islice(list1, 1, 4)]
For small slices, the simple list1[1:4]. If the slices can get quite large it may be better to use an islice to avoid copying the memory
对于小切片,简单的list1[1:4]. 如果切片可以变得非常大,最好使用 islice 来避免复制内存

