简体   繁体   中英

Create two lists from list of tuples

I want to create two lists based on sorted_bounds with every other tuple.

bounds = [1078.08, 1078.816, 1078.924, 1079.348, 1079.448, 1079.476]
sorted_bounds = list(zip(bounds,bounds[1:]))
print(sorted_bounds)
# -> [(1078.08, 1078.816), (1078.816, 1078.924), (1078.924, 1079.348), (1079.348, 1079.448), (1079.448, 1079.476)]

Desired output:

list1 = [(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]  
list2 = [(1078.816, 1078.924), (1079.348, 1079.448)]

How would I do this? I am completely blanking.

list1 = sorted_bounds[0::2]
list2 = sorted_bounds[1::2]

The third value in brackets is "step", so every second element in this case.

Trying to think of a way of doing this in a single pass, but here's a clean way to do it in two passes:

list1 = [x for i, x in enumerate(sorted_bounds) if not i % 2]
list2 = [x for i, x in enumerate(sorted_bounds) if i % 2]
print(list1)
print(list2)

Result:

[(1078.08, 1078.816), (1078.924, 1079.348), (1079.448, 1079.476)]
[(1078.816, 1078.924), (1079.348, 1079.448)]

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