我在 python 中将两个列表列表与一个公共(public)元素合并。
例如我有以下列表:
[[1.0, 'Software Developer', 1256],
[1.0, 'Software Developer', 1329],
[1.0, 'Software Developer', 1469],
[1.0, 'Software Developer', 2086],
[0.9230769230769231, 'United States', 1256],
[0.9230769230769231, 'United States', 1329],
[0.9230769230769231, 'United States', 1469],
[0.9230769230769231, 'United States', 2086]]
和 My Desire 输出如下:
{'ID': 1469,
'Location': 'United States',
'Location_score': 0.9230769230769231,
'title': 'Software Developer',
'title_score': 1.0}
{'ID': 1256,
'Location': 'United States',
'Location_score': 0.9230769230769231,
'title': 'Software Developer',
'title_score': 1.0}
这是我想为所有人做的示例输出。
谁能告诉我如何合并所有列表中最后的所有公共(public)元素。然后在字典中转换列表。
我尝试使用 'Union' 函数。并进行了一些谷歌搜索,但我没有得到正确的答案。
任何人都可以帮助我。
提前致谢
请您参考如下方法:
使用collections.defaultdict:
from collections import defaultdict
lst = [[1.0, 'Software Developer', 1256],
[1.0, 'Software Developer', 1329],
[1.0, 'Software Developer', 1469],
[1.0, 'Software Developer', 2086],
[0.9230769230769231, 'United States', 1256],
[0.9230769230769231, 'United States', 1329],
[0.9230769230769231, 'United States', 1469],
[0.9230769230769231, 'United States', 2086]]
# initialize defaultdict of dicts
d = defaultdict(dict)
# calculate half length of list
n = int(len(lst)/2)
# iterate first part of list
for title_score, title, ID in lst[:n]:
d[ID]['title_score'] = title_score
d[ID]['title'] = title
# iterate second part of list
for Location_score, Location, ID in lst[n: len(lst)]:
d[ID]['Location_score'] = Location_score
d[ID]['Location'] = Location
结果
defaultdict(dict,
{1256: {'Location': 'United States', 'Location_score': 0.9230769230769231,
'title': 'Software Developer', 'title_score': 1.0},
1329: {'Location': 'United States', 'Location_score': 0.9230769230769231,
'title': 'Software Developer', 'title_score': 1.0},
1469: {'Location': 'United States', 'Location_score': 0.9230769230769231,
'title': 'Software Developer', 'title_score': 1.0},
2086: {'Location': 'United States', 'Location_score': 0.9230769230769231,
'title': 'Software Developer', 'title_score': 1.0}})
如果你需要一个字典列表,你可以使用列表理解:
res = [{**{'ID': k}, **v} for k, v in d.items()]
