python - 如何识别Python中两个列表之间的关系/映射?

标签 python python-3.x

我创建了两个列表。

list1= [a,b,c,a,d]
list2=[1,2,3,4,5]

我想根据索引位置找到这两个列表之间的关系,即

在 list1 中 a 重复 2 次索引 0,3 。在 list2 中索引 0,3 值为 1 ,4 关系是一对多:{1,4}

下一个b在列表1中不重复,它的索引是1,列表2索引1值为2 ,关系是一对一的 b:{2}

我的预期输出将是 {a:{1,4},b:{2},c:{3},d:{5}}

最佳答案

我会使用defaultdict :

from collections import defaultdict
list1 = ['a', 'b', 'c', 'a', 'd']
list2 = [1, 2, 3, 4, 5]
result = defaultdict(set)
for value1, value2, in zip(list1, list2):
    result[value1].add(value2)

print(dict(result))

输出

 {'a': {1, 4}, 'b': {2}, 'c': {3}, 'd': {5}}

关于python - 如何识别Python中两个列表之间的关系/映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116334/

相关文章:

javascript - 抓取使用 firebase 数据库的网页

python - 创建插入 mysql 脚本

python - 频率和百分比不均匀组 sns barplot

python - 使用 beautifulsoup 从维基百科表中获取列

python - 为什么变量的显式定义可以调用函数,而迭代器却不行?

python - 使用 Cairo/Pycairo SVG 生成 Inkscape 组/图层?

python - 编译 Boost.Python 快速入门时出错

python-3.x - PyTorch:在训练中添加验证错误

python-3.x - Python(NLTK)-提取名词短语的更有效方法?

python - 如何将数字转换为单词python 3