1

我是 python 的新手,在获取此输出时面临问题

 a = [('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'),('audioVerify', '091;0'), ('imageVerify', 'duck.gif'),('imageVerify', 'egg.gif')]

我想创建一个新列表,该列表应包含所有第 0 个唯一元素,例如

  audioVerify,imageVerify,textVerify

所以预期的结果是

 ['textVerify',(('AH', 'SELECT SERVICES'), ('F7', 'test1>'))  'audioVerify', ('091;0'),  ('imageVerify', ('duck.gif','egg.gif')]
4

4 回答 4

5

你最好使用 a defaultdict

>>> 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',)]})

现在您可以按名称/索引访问其元素:

>>> d['textVerify']
[('AH', 'SELECT SERVICES'), ('F7', 'test1>')]
>>> d['textVerify'][0][0]
'AH'

如果您需要保留字典键的顺序,您可以使用OrderedDict, 连同.setdefault()方法,如 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',)])])
于 2012-11-04T13:24:33.890 回答
2

使用,这至少dict.setdefault()比小型列表要快一些。:defaultdict()

>>> a
[('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'), ('audioVerify', '091;0'), ('imageVerify', 'duck.gif'), ('imageVerify', 'egg.gif')]
>>> d={}
>>> for x in a:
...     d.setdefault(x[0],[]).append(x[1:])
... 
>>> d
{'audioVerify': [('091;0',)], 'textVerify': [('AH', 'SELECT SERVICES'), ('F7', 'test1>')], 'imageVerify': [('duck.gif',), ('egg.gif',)]}

>>> d["audioVerify"]
[('091;0',)]
于 2012-11-04T13:28:37.393 回答
0
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> _ = [d[i[0]].append(i[1:]) for i in a]
>>> d['textVerify']
[('AH', 'SELECT SERVICES'), ('F7', 'test1>')]
于 2012-11-04T13:26:45.507 回答
0
a = [('textVerify', 'AH', 'SELECT SERVICES'), ('textVerify', 'F7', 'test1>'),('audioVerify', '091;0'), ('imageVerify', 'duck.gif'),('imageVerify', 'egg.gif')]

c=set(i[0] for i in a)
d=dict()
for i in c:
        m=[]
        for v in a:
                if v[0]==i:
                        m.extend(list(v[1:]))
        if len(m) !=0:
                d[i]=m

print(d)
于 2012-11-04T16:48:10.337 回答