我希望您将以下列表转换为字典。
sample_list=['A', 'B', 'C', 'D']
预期的字典如下所示
out_dict = {'A':'B','C':'D'}
sample_list=['A', 'B', 'C', 'D']
预期的字典如下所示
out_dict = {'A':'B','C':'D'}
你可以使用:
dict(zip(sample_list[::2], sample_list[1::2]))
zip
函数用于创建新字典的键值对。
zip(it, it)
在列表上成对迭代,然后从中创建字典:it = iter(sample_list)
dct = dict(zip(it, it))
在Python>=3.8中,您将能够使用赋值表达式,并以一个漂亮的一行代码完成所需操作。
dct = dict(zip(it := iter(sample_list), it))
{x:y for x,y in zip(sample_list[::2], sample_list[1::2])}
# {'A': 'B', 'C': 'D'}
假设列表元素个数为偶数,请尝试以下方法:
{ sample_list[i] : sample_list[i+1] for i in range(0, len(sample_list) - 1, 2) }
这个解决方案的优点是在Python 3.x下不会创建中间列表,在Python 2.x中只需用xrange
替换range
即可。
这个示例可以处理不均匀的列表(在正常情况下会导致Python崩溃)
sample_list= ['A', 'B', 'C', 'D','E','F','G','H']
output = {}
for i in range(0,len(sample_list),2):
#print(sample_list[i],sample_list[i+1])
if (i+1) < len(sample_list): #Dont need this line, just avoids python
#crashing if the list isn't even.
temp = {sample_list[i]:sample_list[i+1]}
output.update(temp)
else:
print("ERROR: LIST NOT EVEN, WILL NOT INCL. Last Item.")
print(output)
{'A': 'B', 'C': 'D', 'E': 'F', 'G': 'H'}
您可以使用一个带有迭代器的字典推导:
lst = ['A', 'B', 'C', 'D']
it = iter(lst)
{k: next(it) for k in it}
# {'A': 'B', 'C': 'D'}
{k: v for k, v in zip(it, it)}
怎么样? - Mykola Zotkoit = iter(lst)
。 - Mykola Zotkodct = dict(zip(it := iter(sample_list), it))
。多么美妙啊! - hiro protagonistlst = ['A', 'B', 'C', 'D']
n = { lst[n]:lst[n+1] for n in range(0, len(lst), 2)}
n