Python 如何把几句话合为一句?
有人能帮我改变一下吗:Python 如何把几句话合为一句?,python,Python,有人能帮我改变一下吗: a = [{'one': 4, 'name': 'value1', 'two': 25}, {'one': 2, 'name': 'value1', 'two': 18}, {'one': 1, 'name': 'value1', 'two': 15}, {'one': 2, 'name': 'value2', 'two': 12}, {'one': 1, 'name': 'value2', 'two': 10}] 对这样的事情: b = [{'value1': [(4
a = [{'one': 4, 'name': 'value1', 'two': 25}, {'one': 2, 'name': 'value1', 'two': 18}, {'one': 1, 'name': 'value1', 'two': 15}, {'one': 2, 'name': 'value2', 'two': 12}, {'one': 1, 'name': 'value2', 'two': 10}]
对这样的事情:
b = [{'value1': [(4, 25), (2, 18), (1, 15)]}, {'value2': [(2, 12), (1, 10)]}]
#First create a small dictionary, wich is used to get the keys(name,two,one):
smalld = {'name': 'value1', 'two': 25, 'one': 4}
#Then create the big dict, the dict you are going to get the data
bigd = [{'one': 4, 'name': 'value1', 'two': 25},
{'one': 2, 'name': 'value1', 'two': 18},
{'one': 1, 'name': 'value1', 'two': 15},
{'one': 2, 'name': 'value2', 'two': 12},
{'one': 1, 'name': 'value2', 'two': 10}]
#Then create empty final dict where you
#will use the other dict to create this one
finald = {}
#and now the "magic" loop. k get keys value and run over the big dict to get data.
for k in smalld.iterkeys():
finald[k] = tuple(finald[k] for finald in bigd) #Edited, this line had a mistake
我建议这样做:
b = [{'value1': [(4, 25), (2, 18), (1, 15)]}, {'value2': [(2, 12), (1, 10)]}]
#First create a small dictionary, wich is used to get the keys(name,two,one):
smalld = {'name': 'value1', 'two': 25, 'one': 4}
#Then create the big dict, the dict you are going to get the data
bigd = [{'one': 4, 'name': 'value1', 'two': 25},
{'one': 2, 'name': 'value1', 'two': 18},
{'one': 1, 'name': 'value1', 'two': 15},
{'one': 2, 'name': 'value2', 'two': 12},
{'one': 1, 'name': 'value2', 'two': 10}]
#Then create empty final dict where you
#will use the other dict to create this one
finald = {}
#and now the "magic" loop. k get keys value and run over the big dict to get data.
for k in smalld.iterkeys():
finald[k] = tuple(finald[k] for finald in bigd) #Edited, this line had a mistake
试试这个:
>>> di = {}
>>> for i in a:
... if di.get(i['name']):
... di[i['name']].append((i['one'], i['two']))
... else:
... di[i['name']] = []
... di[i['name']].append((i['one'], i['two']))
输出:
{'value2': [(2, 12), (1, 10)], 'value1': [(4, 25), (2, 18), (1, 15)]}
我是新手。我不知道如何开始“dict_keys”对象不支持索引”我使用Python3Oh!,但是我已经在Python2.7上测试了它。Python3中没有“has_key”,如何用“in”替换这一行?@user29438使用get代替。