试图理解字典时语法无效?

问题描述 投票:0回答:1
test_list_k = ['a', 'b', 'c', 'd']

test_list_v = ['f', 'g', 'h']

test_dict_comp = {k: v for k in test_list_k and for v in test_list_v}
print(test_dict_comp)

由于某种原因,它将test_dict_comp中的第二个视为无效语法。

python dictionary dictionary-comprehension
1个回答
0
投票

假设目标是使用dict中的值制作test_list_k中的test_list_v配对密钥,您想要的是zip(它将删除未配对的密钥)或itertools.zip_longest(将允许您使用为未配对的密钥提供填充值)。使用它的语法是:

© www.soinside.com 2019 - 2024. All rights reserved.