Python list comprehension - access last created element?

后端 未结 7 1997
无人共我
无人共我 2020-12-14 17:31

Is it possible to access the previous element generated in a list comprehension.

I am working on some toy encryption stuff. Given the key as an arbitrarily large in

相关标签:
7条回答
  • 2020-12-14 18:35

    Here is an example how to access the last and next created elements in a list comprehension using enumerate.

    The previous value...

    Here -1 is the offset and None is the default value.

    A = ['A','B','C','D','E','F','G','H','I','J']
    [(A[i-1] if (i-1) >= 0 else None,x) for i,x in enumerate(A)
    

    Output as tuple (Previous, Current)

    [(None, 'A'), ('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J')]

    The next value...

    A = ['A','B','C','D','E','F','G','H','I','J']
    [(x, A[i+1] if (i+1) < len(A) else None) for i,x in enumerate(A)]
    

    Output as tuple (Current, Next)

    [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J'), ('J', None)]

    This is very similar to the lag() and lead() analytical functions in sql.

    0 讨论(0)
提交回复
热议问题