如何删除元组列表中的重复项

时间:2016-10-14 08:02:28

标签: list python-2.7 dictionary tuples defaultdict

我一直在尝试使用defaultdict / dictionary set来删除副本,但是,我无法实现所需的输出。我将在下面详细说明。我希望删除下面元组列表中的重复:

List of tuples: [('Samsung', 'Handphone'), ('Samsung', 'Handphone),('Samsung','Tablet'),('Sony','Handphone')]

我想要的输出是:

Output: {('Samsung','Handphone','Tablet'),('Sony','Handphone')}

我想删除元组中的重复值,并附加" tablet"和#34;三星"在一个元组中,因为它属于同一家公司。我尝试过使用defaultdict / dictionary。但是我无法得到它。我该怎么做呢?我想欢迎您提出任何建议或想法。谢谢。

2 个答案:

答案 0 :(得分:2)

正如@cco所说,你想要的输出是不可能的,如果你想用你的字典做进一步的分析,那么拥有键和值是最好的主意,

试试这个,

from collections import defaultdict
a=[('Samsung', 'Handphone'), ('Samsung', 'Handphone'),('Samsung','Tablet'),('Sony','Handphone')]
a=list(set(a))
final={}
dic=defaultdict(list)
for k,v in a:
    dic[k].append(v)

for l,m in dic.iteritems():
    final[l]=m
print final

输出:

{'Sony': ['Handphone'], 'Samsung': ['Tablet', 'Handphone']}

答案 1 :(得分:1)

d = {}
t0 = [('Samsung', 'Handphone'), ('Samsung', 'Handphone'),('Samsung','Tablet'),('Sony','Handphone')]
for t in t0:
    d.setdefault(t[0], set()).add(t[1])
print(tuple(tuple([k]+list(v)) for k, v in d.items()))

打印

(('Sony', 'Handphone'), ('Samsung', 'Handphone', 'Tablet'))

尽可能接近您想要的输出(您的确切请求是不可能的,因为{}文字包含字典或集合,并打印带有这些元组作为内容的集合文字给出了这个:

set([('Sony', 'Handphone'), ('Samsung', 'Handphone', 'Tablet')])

这不是你要求的,虽然它与设定文字相同

{('Sony', 'Handphone'), ('Samsung', 'Handphone', 'Tablet')}
相关问题