In Python list comprehension is it possible to access the item index?

后端 未结 3 1724
慢半拍i
慢半拍i 2021-01-31 13:15

Consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1:

for ind, obj in enum         


        
相关标签:
3条回答
  • 2021-01-31 13:28

    Unless your real use case is more complicated, you should just use a list slice as suggested by @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

    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

    0 讨论(0)
  • 2021-01-31 13:37

    If you use enumerate, you do have access to the index:

    list2 = [x for ind, x in enumerate(list1) if 4>ind>0]
    
    0 讨论(0)
  • 2021-01-31 13:44
    list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0]
    
    0 讨论(0)
提交回复
热议问题