简体   繁体   中英

Python tuple to dictionary with elements in tuples as keys and assigning fixed values to return keys with max and min rolling sum of values

I am having an issue in converting a dataset in python where I think having them from tuple to keys and assigning some fixed values are going to help me. To give a small example, I have the following input data as arrays of tuples (not necessarily sorted):

[(1,3), (2,7), (10, 15)]

The output I want is, for first element of each tuple, I want them assigned value 1 while for the 2nd element of each tuple, I want them assigned value of -1, that is the output I want will be a dictionary like the following:

{1:1, 3:-1, 2:1, 7:-1, 10:1, 15:-1}

Then I want to sort this dictionary with the keys and return keys and values with maximum and minimum of rolling sum. I think I shall be able to figure out this part however, I am stuck with the needed tuple to dictionary conversion as I stated above. Does anyone have any suggestion or solution?

Something like this?

# initialize variables:
tuple_list = [(1,3), (2,7), (10, 15)]
data = {}

# iterate over each point (tuple) in tuple_list:
for point in tuple_list:

    data[point[0]] = 1
    data[point[1]] = -1

print(data)

Itertools will make short work of stuff like this. You can cycle through (1, -1) with cycle() and flatten the original with chain() . Then zip the together:

from itertools import chain, cycle

l = [(1,3), (2,7), (10, 15)]

dict(zip(chain(*l), cycle([1, -1])))

# {1: 1, 3: -1, 2: 1, 7: -1, 10: 1, 15: -1}

This can work also:

d={}
lst = [(1,3), (2,7), (10, 15)]

for x in lst: d={**d,x[0]:1,x[1]:-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