包含元组的Python拆分列表

出现一个完全由元组组成的列表,例如:'

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.

那怎么办呢?

评论
lillo
lillo

This can be done relatively efficiently with a supporting dict:

def split_by_idx(items, idx=2):
   result = {}
   for item in items:
       key = item[idx]
       if key not in result:
           result[key] = []
       result[key].append(item)
   return result

and the lists can be collected from result with dict.values():

d = split_by_idx(lst)
print(list(d.values()))
点赞
评论
fharum
fharum

You could use a defaultdict to group by colour:

from collections import defaultdict

lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue"), ("yo", "Green")]

colours = defaultdict(list)
for word, colour in lst:
    colours[colour].append((word, colour))

print(colours)
# defaultdict(<class 'list'>, {'Blue': [('hello', 'Blue'), ('hey', 'Blue')], 'Red': [('hi', 'Red')], 'Green': [('yo', 'Green')]})
点赞
评论
dquia
dquia

你可以这样做:

lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue"), ("yo", "Green")]
colors = {elem[1] for elem in lst}

lsts = []

for color in colors:
    color_lst = [elem for elem in lst if elem[1] == color]
    lsts.append(color_lst)

colors contains the unique colors present in lst, and lsts will contain the final 3 lists you need.

Here is what lsts ends up being: [[('hi', 'Red')], [('yo', 'Green')], [('hello', 'Blue'), ('hey', 'Blue')]].

点赞
评论