出现一个完全由元组组成的列表,例如:'
lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue), ("yo", "Green")]
How can I split lst
into as many lists as there are colours? In this case, 4 lists
[("hello", "Blue"), ("hey", "Blue)]
[("hi", "Red")]
[("yo", "Green")]
我只需要稍后才能使用这些列表,所以我不想只将它们输出到屏幕上。
有关列表的详细信息
I know that every element of lst
is strictly a double-element tuple. The colour is also always going to be that second element of each tuple. Problem is,lst
is dependant on user input, so I won't always know how many colours there are in total and what they are. That is why I couldn't predefine variables to store these lists in them.
那怎么办呢?
This can be done relatively efficiently with a supporting
dict
:and the lists can be collected from
result
withdict.values()
:You could use a
defaultdict
to group by colour:你可以这样做:
colors
contains the unique colors present inlst
, andlsts
will contain the final 3 lists you need.Here is what
lsts
ends up being:[[('hi', 'Red')], [('yo', 'Green')], [('hello', 'Blue'), ('hey', 'Blue')]]
.