Making a dictionary of arrays with two lists with Python
本问题已经有最佳答案,请猛点这里访问。
我有一个特别的问题使我很难解决。假设我有以下两个列表:
1 2 | x = ["A","B","C","D","E"] y = [1,2,3,2,1] |
我要做的是创建一个键值关系,其中
1 2 | mapping = dict(zip(y,x)) {1: 'E', 2: 'D', 3: 'C'} |
这将覆盖上一个字母。我希望能够返回以下内容:
1 | {1:['A','E'], 2:['B','D'], 3:['C']} |
有人对此有聪明的解决办法吗?最好不使用Itertools。
您可以使用
1 2 3 4 5 6 | x = ["A","B","C","D","E"] y = [1,2,3,2,1] d = {} for i,j in zip(y,x): d.setdefault(i, []).append(j) print d |
输出:
1 | {1: ['A', 'E'], 2: ['B', 'D'], 3: ['C']} |
我喜欢这样的情况。
1 2 3 4 5 6 7 8 9 10 | from collections import defaultdict x = ["A","B","C","D","E"] y = [1,2,3,2,1] D = defaultdict(list) for i, j in zip(x, y): D[j].append(i) print dict(D) |
输出为:
1 | {1: ['A', 'E'], 2: ['B', 'D'], 3: ['C']} |
这里有一个聪明的,但
1 2 3 4 | >>> x = ["A","B","C","D","E"] >>> y = [1,2,3,2,1] >>> {y[i] : [x[j] for j in range(len(y)) if y[j] == y[i]] for i in range(len(y))} {1: ['A', 'E'], 2: ['B', 'D'], 3: ['C']} |
就其价值而言,@joe r和@mattingly890解决方案是可行的,因为它们是
这里有一个简单(不聪明)的解决方案。我认为一个简单的解决方案更符合Python的哲学,而不是一个聪明的解决方案。Perl是一种旨在最大限度地提高智能性的语言,imho,我发现它几乎是不可读的(诚然,如果我是一个没有经验的Perl程序员的话,我会避开它)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | x = ["A","B","C","D","E"] y = [1,2,3,2,1] assert(len(x) == len(y)) d = {} for i in range(len(x)): key = y[i] val = x[i] if key in d: d[key].append(val) else: d[key] = [val, ] print d |