我有一个列表如下:
my_list = [
[1, 'green', 'orange', 'blue']
[2, 'orange', 'black']
[1, 'green', 'pink' ]
[3, 'white']
[2, 'purple', 'yellow', 'black']
]
所以,我需要在my_list中添加另一个列表,如下所示:
output_list = [
[1, 'green', 'orange', 'blue', 'pink']
[2, 'orange', 'black', 'purple', 'yellow']
[3, 'white']
]
有一种有效的方法来计算my_list非常大吗?我的意思是哪种方法应该更好而不是使用两个嵌套的for循环?我不期待一些代码,只是想法!
THX。
答案 0 :(得分:4)
my_list = [
[1, 'green', 'orange', 'blue'],
[2, 'orange', 'black'],
[1, 'green', 'pink' ],
[3, 'white'],
[2, 'purple', 'yellow', 'black']
]
values = set(map(lambda x:x[0], my_list))
newlist = [[x] + list(set(sum([y[1:] for y in my_list if y[0] == x], []))) for x in values]
print newlist
它是如何运作的?
set(map(lambda x:x[0], my_list)
创建一个包含[1, 2, 3]
的集合 - my_list
中每个列表的第一个元素。
然后,我们使用values
获取[___ for x in values]
的每个值。
对于值中的每个值,我们遍历my_list
并添加0
元素等于x
的所有列表。 (当然,0
元素本身除外)
然后,我们列出了一系列清单:
[[['green', 'orange', 'blue'], ['green', 'pink']], [['orange', 'black'], ['purple', 'yellow', 'black']], [['white']]]
因此,我们使用sum(the_list, [])
连接每个第三维列表。
然后我们要删除重复项,所以:
list(set(sum(the_list, [])))
我们最终得到:
[list(set(sum([y[1:] for y in my_list if y[0] == x], []))) for x in values]
唯一剩下的就是将第一个元素(x
本身)添加到任何子列表中,所以
[[x] + ... for x in values]
我们终于得到了:
[[x] + list(set(sum([y[1:] for y in my_list if y[0] == x], []))) for x in values]
答案 1 :(得分:1)
这应该做你想要的:
output_list = []
for lst in my_list:
for l in output_list:
if l[0] == lst[0]:
for item in lst:
if item not in l:
l.append(item)
break
else:
output_list.append(lst)
答案 2 :(得分:0)
我在评论中说过,tobias_k的建议可能是最有效的,但从未提供任何代码......这就是我要做的事情:
out = {} #output dictionary can be converted back to a list later
for item in my_list: #for each sublist
k = item[0] #first item is our dict key
l = item[1:] #rest of the list is data
new = out.get(k, set()) #get whatever is at out[k] or return an empty set if nothing is there yet
new.update(l) #add the items from l (sets will automatically trash duplicates)
out[k] = new #set out[k] to our newly updated set