简体   繁体   中英

Convert Python 1D List to tuple pair

I have a list of integers:

[0, 6, 43, 10, 48, 1]

and I want to convert it to tuple pairs like this:

[(0, 6), (6,43), (43,10), (10,48), (48,1)]

I tried this solution zip(shortest_path[::2], shortest_path[1::2]) however doesn't overlap the elements. For example, in the tuple example above, each element is repeated twice except the first and last.

Thanks

Using zip and slice notation:

data = [0, 6, 43, 10, 48, 1]
output = list(zip(data, data[1:]))

[(0, 6), (6, 43), (43, 10), (10, 48), (48, 1)]

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