通过将两个长度不均匀的列表压缩在一起来创建字典

Mat*_*Mat 29 python zip dictionary list

我有两个不同长度的列表,L1和L2.L1比L2长.我想得到一个字典,其中L1的成员作为键,L2的成员作为值.

只要L2的所有成员都用完了.我想重新开始并重新开始使用L2 [0].

L1 = ['A', 'B', 'C', 'D', 'E']    
L2 = ['1', '2', '3']    
D = dict(zip(L1, L2))    
print(D)
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,输出是这样的:

{'A': '1', 'B': '2', 'C': '3'}
Run Code Online (Sandbox Code Playgroud)

我想要实现的目标如下:

{'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 36

使用itertools.cycle循环周围的开头L2:

from itertools import cycle
dict(zip(L1, cycle(L2)))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,连接L2自身也有效.

# dict(zip(L1, L2 * 2))
dict(zip(L1, L2 + L2))
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)


Dan*_*ejo 24

使用itertools.cycle:

from itertools import cycle

L1 = ['A', 'B', 'C', 'D', 'E']
L2 = ['1', '2', '3']

result = dict(zip(L1, cycle(L2)))

print(result)
Run Code Online (Sandbox Code Playgroud)

产量

{'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以使用枚举和索引L2模数的长度L2:

result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
print(result)
Run Code Online (Sandbox Code Playgroud)


sch*_*ggl 15

cycle 很好,但我会添加这个基于模的方法:

{L1[i]: L2[i % len(L2)] for i in range(len(L1))]}
Run Code Online (Sandbox Code Playgroud)


Roa*_*ner 7

您还可以使用a collections.deque()创建循环FIFO队列:

from collections import deque

L1 = ['A', 'B', 'C', 'D', 'E']    
L2 = deque(['1', '2', '3'])

result = {}
for letter in L1:
    number = L2.popleft()
    result[letter] = number
    L2.append(number)

print(result)
# {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)

弹出当前最左侧的项目,L2并在将数字添加到词典后将其追加到最后.

注:这两个collections.deque.popleft()collections.deque.append()是O(1)操作,所以上面仍然是O(N),因为你需要遍历所有元素L1.


iGi*_*ian 5

其他选项没有for循环的依赖性:

D = {}
for i, e in enumerate(L1):
  D[e] = L2[i%len(L2)]

D #=> {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)

要不就:

{ e: L2[i%len(L2)] for i, e in enumerate(L1) }
#=> {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}
Run Code Online (Sandbox Code Playgroud)