从python中的列表列表中提取值

时间:2018-11-24 11:18:14

标签: python dictionary

我的列表如下:

mylist = [
    ['OF', 'O'],
    ['ODH', 'O'],
    ['1937066911', 'NUMBER'],
    ['FLOYD', 'PERSON'],
    ['WESLEY', 'PERSON'],
    ['MCGRAW', 'PERSON'],
    ['04', 'NUMBER'],
    ['RUTH', 'PERSON'],
    ['MAE', 'PERSON'],
    ['MCGRAW', 'PERSON']
]

这是所需的输出

desired_output = [
    {'O':'OF', 'ODH'},
    {'NUMBER':'1937066911'},
    {'PERSON':'FLOYD','WESLEY','MCGRAW'},
    {'NUMBER':'04'},
    {'PERSON':'RUTH','MAE','MCGRAW'}
]

这是我尝试过的:

import json
from collections import defaultdict
import itertools
new_dict = defaultdict(list)

with open('A.json') as jsonfile:
    file_data = json.load(jsonfile)
    for d in range(len(file_data)):
       try:
          if file_data[d][1] in file_data[d+1]:
            new_dict[file_data[d][1]].append(file_data[0])
       except:
             pass
    print(new_dict)

注意A.json具有如上所示的列表列表

2 个答案:

答案 0 :(得分:0)

您可以使用groupby,假设您想要一个列出值列表的字典:

from operator import itemgetter
from itertools import groupby

lst = [['OF', 'O'], ['ODH', 'O'], ['1937066911', 'NUMBER'], ['FLOYD', 'PERSON'], ['WESLEY', 'PERSON'],
          ['MCGRAW', 'PERSON'], ['04', 'NUMBER'], ['RUTH', 'PERSON'], ['MAE', 'PERSON'], ['MCGRAW', 'PERSON']]

result = [{ k : list(map(itemgetter(0), group))} for k, group in groupby(lst, key=itemgetter(1))]
print(result)

输出

[{'O': ['OF', 'ODH']}, {'NUMBER': ['1937066911']}, {'PERSON': ['FLOYD', 'WESLEY', 'MCGRAW']}, {'NUMBER': ['04']}, {'PERSON': ['RUTH', 'MAE', 'MCGRAW']}]

答案 1 :(得分:0)

我们在这里能做的最好的事情就是将列表作为值的字典列表。

from itertools import groupby
from operator import itemgetter

mylist = [['OF', 'O'],['ODH', 'O'],['1937066911', 'NUMBER'],['FLOYD', 'PERSON'],['WESLEY', 'PERSON'],['MCGRAW', 'PERSON'],['04', 'NUMBER'],['RUTH', 'PERSON'],['MAE', 'PERSON'],['MCGRAW', 'PERSON']]
first = itemgetter(0)
second = itemgetter(1)
result = []

for key, group in groupby(mylist, key=second):
    result.append({key:[first(g) for g in group]})

结果:

>>> result
[{'O': ['OF', 'ODH']},
 {'NUMBER': ['1937066911']},
 {'PERSON': ['FLOYD', 'WESLEY', 'MCGRAW']},
 {'NUMBER': ['04']},
 {'PERSON': ['RUTH', 'MAE', 'MCGRAW']}]