如何将两个独立列表转换为单个字典列表?(附Python示例)
Yes, this is absolutely achievable!
You can easily create the desired list l3 by pairing elements from l1 and l2 using Python's built-in zip() function along with a list comprehension. Here's how:
l1 = ['R21', 'R21', 'R21', 'R22', 'R22', 'R22', 'R23', 'R23', 'R23'] l2 = ['T/T/T/T', 'G/G/G/G', 'CA/CA/CA/CA', 'G/G/G/G', 'TA/TA/TA/TA', 'T/T/T/T', 'TAA/TAA/TAA/TAA', 'C/C/C/C', 'T/T/T/T'] # Create l3 by zipping l1 and l2 into dictionaries l3 = [ {key: value} for key, value in zip(l1, l2) ] print(l3)
Output:
[{'R21': 'T/T/T/T'}, {'R21': 'G/G/G/G'}, {'R21': 'CA/CA/CA/CA'}, {'R22': 'G/G/G/G'}, {'R22': 'TA/TA/TA/TA'}, {'R22': 'T/T/T/T'}, {'R23': 'TAA/TAA/TAA/TAA'}, {'R23': 'C/C/C/C'}, {'R23': 'T/T/T/T'}]
How it works:
zip(l1, l2)iterates over both lists simultaneously, pairing each element froml1with the corresponding element at the same index inl2.- The list comprehension
[ {key: value} ... ]takes each pair and wraps them into a single-key dictionary, collecting all these dictionaries into the final listl3.
This approach is efficient, readable, and directly produces the exact output you're looking for.
内容的提问来源于stack exchange,提问作者Mandie Driskill
相关产品推荐
相关产品推荐

