我正在尝试根据他们的语言对所有这些进行分组
[('Lanice', 'Montre', '[email protected]', 'en'),
('Do', 'Ji', '[email protected]', 'es'),
('Edem', 'Lamoine', '[email protected]', 'zh-Hans'),
('Celine', 'Jerry', 'yoyoyogmail.com', 'ar'),
('Kerry', 'Mabs', '[email protected]', 'ar'),
('Tom', 'Maine', '[email protected]', 'fr'),
('Mary', 'Maine', '[email protected]', 'fr'),
('John', 'Doe', '[email protected]', 'bg'),
('Johnny','Bravo', '[email protected]', 'en')]
输出将是这样的: 输出=
[{"en": ['[email protected]', '[email protected]']},
{"es": ["[email protected]"]},
{"zh-Hans": ['[email protected]']},
...]
使语言词典独一无二
您可以使用
collections.defaultdict
:
from collections import defaultdict
output = defaultdict(list)
for *_, mail, lang in data:
output[lang].append(mail)
defaultdict(<class 'list'>, {'en': ['[email protected]', '[email protected]'],
'es': ['[email protected]'],
'zh-Hans': ['[email protected]'],
'ar': ['[email protected]', '[email protected]'],
'fr': ['[email protected]', '[email protected]'],
'bg': ['[email protected]']})
data = [('Lanice', 'Montre', '[email protected]', 'en'),
('Do', 'Ji', '[email protected]', 'es'),
('Edem', 'Lamoine', '[email protected]', 'zh-Hans'),
('Celine', 'Jerry', '[email protected]', 'ar'),
('Kerry', 'Mabs', '[email protected]', 'ar'),
('Tom', 'Maine', '[email protected]', 'fr'),
('Mary', 'Maine', '[email protected]', 'fr'),
('John', 'Doe', '[email protected]', 'bg'),
('Johnny','Bravo', '[email protected]', 'en')]
也许有帮助:
output = {_user[-1]:[] for _user in data}
[output[_user[-1]].append(_user[2]) for _user in data]
print(output)
结果:
{
'en': ['[email protected]', '[email protected]'],
'es': ['[email protected]'],
'zh-Hans': ['[email protected]'],
'ar': ['[email protected]', '[email protected]'],
'fr': ['[email protected]', '[email protected]'],
'bg': ['[email protected]']
}