在python中列出重复的数据串联 [英] List duplicate data concatenation in python
本文介绍了在python中列出重复的数据串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python的新手,在获取此输出时遇到问题
i am a newbie in python and facing issue in getting this output
a = [('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'),('audioVerify', '091;0'), ('imageVerify', 'duck.gif'),('imageVerify', 'egg.gif')]
我想创建一个新列表,其中应包含所有第0个唯一元素,例如
i want to create a new list which should hold all the 0th unique element like
audioVerify,imageVerify,textVerify
所以预期的结果是
['textVerify',(('AH', 'SELECT SERVICES'), ('F7', 'test1>')) 'audioVerify', ('091;0'), ('imageVerify', ('duck.gif','egg.gif')]
推荐答案
您最好使用 defaultdict
为此:
You'd better use a defaultdict
for this:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for item in a:
... d[item[0]].append(item[1:])
...
>>> d
defaultdict(<class 'list'>, {'textVerify': [('AH', 'SELECT SERVICES'),
('F7', 'est1>')], 'imageVerify': [('duck.gif',), ('egg.gif',)],
'audioVerify': [('091;0',)]})
现在您可以按名称/索引访问其元素:
Now you can access its elements by name/index:
>>> d['textVerify']
[('AH', 'SELECT SERVICES'), ('F7', 'test1>')]
>>> d['textVerify'][0][0]
'AH'
If you need to preserve the order of the dictionary keys, you can use an OrderedDict
, together with the .setdefault()
method, as described by Ashwini Chaudhary:
>>> d = OrderedDict()
>>> for x in a:
... d.setdefault(x[0],[]).append(x[1:])
...
>>> d
OrderedDict([('textVerify', [('AH', 'SELECT SERVICES'), ('F7', 'test1>')]),
('audioVerify', [('091;0',)]), ('imageVerify', [('duck.gif',), ('egg.gif',)])])
这篇关于在python中列出重复的数据串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文