简体   繁体   中英

Enumerate and Zip to access previous index

When using zip do you need to use enumerate and convert the zip tuples to a list to access the previous index (ie index -1)

eg

list1 = [1, 3, 4, 8, 10]
list2 = [1, 3, 6, 7, 9]

combined_list = list(zip(list1, list2))

for i, v in enumerate(combined_list):
    if i > 0:
        print(combined_list[i-1])

Put simply, is that the most pythonic way?

list slice, or enumerate's second parameter, as pointed out before.

for i, v in enumerate( combined_list[1:] ):
    print( i, v, i-1, combined_list[i] )

for i, v in enumerate( combined_list, 1 ):
    print( i, v, i-1, combined_list[i] )

0 (3, 3) -1 (1, 1)
1 (4, 6) 0 (3, 3)
2 (8, 7) 1 (4, 6)
3 (10, 9) 2 (8, 7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM