Extract different values from list of tuples

情到浓时终转凉″ 提交于 2019-12-23 16:21:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!