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代码,我使用这些代码添加了一个新的清单2,其中列出了清单1中从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?
如果我无法通过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]
3 个解决方案
#1
118
list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
#2
27
If you use enumerate
, you do have access to the index:
如果使用enumerate,你确实可以访问索引:
list2 = [x for ind, x in enumerate(list1) if 4>ind>0]
#3
2
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
对于小片,简单的列表1[1:4]。如果切片可以变得非常大,那么最好使用islice来避免复制内存
#1
118
list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
#2
27
If you use enumerate
, you do have access to the index:
如果使用enumerate,你确实可以访问索引:
list2 = [x for ind, x in enumerate(list1) if 4>ind>0]
#3
2
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
对于小片,简单的列表1[1:4]。如果切片可以变得非常大,那么最好使用islice来避免复制内存