问题
How to extract a list of different values from following list of tuples?
tuple = ((("test", 123), ("test", 465), ("test", 8910), ("test2", 123)))
I want to get a list like:
different_values = ("test", "test2")
Now I want to access all values by this "keys" and get them by a list:
test_values = (123, 456, 8910)
test2_values = (123)
How to do that?
回答1:
I'd transform your data to a dictionary of lists:
d = {}
for k, v in tuples:
d.setdefault(k, []).append(v)
Now you can access the keys as d.keys()
, and the list of values for each key k
as d[k]
.
(Shortly, someone will step forward and claim a defaultdict
would be better for this. Don't listen to them, it simply doesn't matter in this case.)
来源:https://stackoverflow.com/questions/9226931/extract-different-values-from-list-of-tuples