1

In given code, I am extracting first column from data_points list which contains a dictionary. The keys of the dictionary contain a tuple of (x,y) coordinates. I extract minX and minY from the keys. How can I compress the code?

    x_list = []
    y_list = []
    keys = data_points[0].keys()
    for i in keys:
        x_list.append(i[0])
        y_list.append(i[1]) 

    min_value = (min(x_list), min(y_list))
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Pandey Rashmi
  • 147
  • 1
  • 4
  • 14
  • 1
    I do not think this is dupe of the listed post, which is why I listed that post in my response, but did not mark this as a dupe of same. OP needs to separate a list of tuples. Question wasn't clear on that, but that is what the code shows. – Stephen Rauch Jan 10 '17 at 08:39

1 Answers1

1

zip can be used to combine, as well as, separate lists/tuples. You did not give any sample data so I will assume:

data_points = [{
    (3, 0): None,
    (1, 2): None,
}]
keys = data_points[0].keys()

A one line equivalent to your code which splits the tuples and gets the mins is:

min_value = (min(zip(*keys)[0]), min(zip(*keys)[1]))

There are some caveats with zip in python 2 and its creation of potentially large intermediate structures. See here for some more info.

Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135