Python 中的分组项目

问题描述 投票:0回答:2

我正在尝试根据他们的语言对所有这些进行分组

        [('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]']},
      ...]

使语言词典独一无二

python arrays sorting
2个回答
4
投票

您可以使用

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

1
投票
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]']
}
© www.soinside.com 2019 - 2024. All rights reserved.