简体   繁体   中英

How to convert each pair of list into tuple in python

I want to convert list = [1,4,2,3,0] to list_tup = [(1,4),(4,2),(2,3),(3,0)] . You can see my code below but it outputs [(1,4),(2,3)] . I am wondering how to adjust indices in zip.

list=[1,4,2,3,0]
list_tup = tuple(zip(list[0::2], list[1::2]))

Try zipping the whole list with the list without the first element:

l = [1,4,2,3,0]
print(list(zip(l, l[1:])))

Or use unpack * :

l = [1,4,2,3,0]
print([*zip(l, l[1:])])

They both output:

[(1, 4), (4, 2), (2, 3), (3, 0)]

Try Zipping whole list without first element of the list

l = [1,4,2,3,0] print(list(zip(l, l[1:])))

output:

[(1, 4), (4, 2), (2, 3), (3, 0)]

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