Python 总结列表中的信息
假设我有一个列表:Python 总结列表中的信息,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,假设我有一个列表: INPUT=[{'id': 1, 'context': 'this is q1', 'content': 'this is ch1'}, {'id': 1, 'context': 'this is q1', 'content': 'this is ch2'}, {'id': 1, 'context': 'this is q1', 'content': 'this is ch3'}, {'id': 2, 'context': 'this is q12', 'content':
INPUT=[{'id': 1, 'context': 'this is q1', 'content': 'this is ch1'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch2'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch3'},
{'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}]
转换:
OUTPUT=[{'id': 1, 'context': 'this is q1', 'content': ['this is ch1','this is ch2','this is ch3']},
{'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}]
python上执行上述转换的最简单方法是什么?使用itertools.groupby
演示:
输出:
我建议您使用以下简短易读的解决方案:
from collections import defaultdict
INPUT=[
{'id': 1, 'context': 'this is q1', 'content': 'this is ch1'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch2'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch3'},
{'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}]
# Create first a dictionary:
# - with tuples (id,context) as key
# - with the appended contents as value
newDict = defaultdict(list)
for d in INPUT:
newDict[(d['id'],d['context'])].append(d['content'])
# Convert this dictionary into a list of dictionaries with expected keys
OUTPUT = [{'id':k[0], 'context':k[1], 'content':v} for k,v in newDict.items()]
print(OUTPUT)
# [{'id': 1, 'context': 'this is q1', 'content': ['this is ch1', 'this is ch2', 'this is ch3']},
# {'id': 2, 'context': 'this is q12', 'content': ['this is ch14']}]
试试这个
for i in range(len(INPUT)):
INPUT[i]['content'] = [INPUT[i]['content']]
print(INPUT[i]['content'])
上面的转换是什么?你的问题是什么一点也不清楚。这里发生了什么一点也不清楚。您似乎在第一本词典内容的列表中按“这是ch14”列出所有内容。这就是你的意思吗?或者你是在试图把字典的列表合并在一起以形成内容?这个问题提供了多种方法来合并字典中的列表:请澄清您的具体问题或添加额外的详细信息,以突出您所需要的内容。您需要尝试更详细地解释您需要实现的内容。看看这里如何问一个好问题
from collections import defaultdict
INPUT=[
{'id': 1, 'context': 'this is q1', 'content': 'this is ch1'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch2'},
{'id': 1, 'context': 'this is q1', 'content': 'this is ch3'},
{'id': 2, 'context': 'this is q12', 'content': 'this is ch14'}]
# Create first a dictionary:
# - with tuples (id,context) as key
# - with the appended contents as value
newDict = defaultdict(list)
for d in INPUT:
newDict[(d['id'],d['context'])].append(d['content'])
# Convert this dictionary into a list of dictionaries with expected keys
OUTPUT = [{'id':k[0], 'context':k[1], 'content':v} for k,v in newDict.items()]
print(OUTPUT)
# [{'id': 1, 'context': 'this is q1', 'content': ['this is ch1', 'this is ch2', 'this is ch3']},
# {'id': 2, 'context': 'this is q12', 'content': ['this is ch14']}]
for i in range(len(INPUT)):
INPUT[i]['content'] = [INPUT[i]['content']]
print(INPUT[i]['content'])