python - 形成一个字典,键来自列表,值是 Python 中另一个列表中项目的出现

标签 python list dictionary count

给定两个长度相同的列表:

List1 = ['a','b','c','d','b','a','b','c']
List2 = ['1','2','3','4','5','6','7','8']

我想将 a dict 输出为:

dic = {'a':['1','6'], 'b':['2','5','7'], 'c':['3','8'], 'd':['4']}

如何用Python实现?谢谢!

最佳答案

您可以使用 zip 函数创建一个列列表(在 python 3.X 中是一个迭代器)并使用 dict.setdefault方法(或 collections.defaultdict)创建一个愿望字典:

>>> List1 = ['a','b','c','d','b','a','b','c']
>>> List2 = ['1','2','3','4','5','6','7','8']
>>> 
>>> d={}
>>> for i,j in zip(List1,List2):
...   d.setdefault(i,[]).append(j)
... 
>>> d
{'a': ['1', '6'], 'c': ['3', '8'], 'b': ['2', '5', '7'], 'd': ['4']}

如果您关心顺序,您可以使用 collections.OrderedDict :

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in zip(List1,List2):
...   d.setdefault(i,[]).append(j)
... 
>>> d
OrderedDict([('a', ['1', '6']), ('b', ['2', '5', '7']), ('c', ['3', '8']), ('d', ['4'])])
>>> 

关于python - 形成一个字典,键来自列表,值是 Python 中另一个列表中项目的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925474/

相关文章:

java - 将 List<Map<Long, String>> 转换为 List<Long> Java 8

python - Pandas Dataframe 到具有多个键的字典

python - Numba 与 Cython 循环优化

python - 使用 for 循环在 PIL 上打开多个图像

c - 将 char* 添加到链表不起作用

list - 序言列表高原

javascript - 通过 JSON 将 javascript 参数字典发送到 MVC Controller

python - PySpark 2 - 正则表达式替换之前的所有内容 <BR>

python - 在 numpy 数组中查找唯一点

MYSQL 获取当前星期几在列表中的项目