将字符串列表转换成字典,以奇数索引的字符串作为键,以偶数索引的字符串作为值的Pythonic方法? [英] Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?
问题描述
我有一个从某处解析的字符串列表,格式如下:
I have a list of strings parsed from somewhere, in the following format:
[key1, value1, key2, value2, key3, value3, ...]
我想基于此列表创建字典,如下所示:
I'd like to create a dictionary based on this list, like so:
{key1:value1, key2:value2, key3:value3, ...}
一个普通的带有索引偏移量的for
循环可能会解决这个问题,但是我想知道是否有Pythonic的方式可以做到这一点.列表理解似乎很有趣,但是我似乎找不到如何将它们应用于这个特定问题的方法.
An ordinary for
loop with index offsets would probably do the trick, but I wonder if there's a Pythonic way of doing this. List comprehensions seem interesting, but I can't seem to find out how to apply them to this particular problem.
有什么想法吗?
推荐答案
您可以尝试:
dict(zip(l[::2], l[1::2]))
说明:我们将列表分为两个列表,一个是偶数,另一个是奇数元素,方法是从第一个或第二个元素(即l[::2]
和l[1::2]
).然后,我们使用内置的zip
将两个列表分成一个成对的列表.最后,我们调用dict
从这些键值对创建字典.
Explanation: we split the list into two lists, one of the even and one of the odd elements, by taking them by steps of two starting from either the first or the second element (that's the l[::2]
and l[1::2]
). Then we use the zip
builtin to the two lists into one list of pairs. Finally, we call dict
to create a dictionary from these key-value pairs.
时间为~4n
,空间为~4n
,包括最后的字典.但是,由于zip
,dict
和切片运算符是用C编写的,因此它可能比循环更快.
This is ~4n
in time and ~4n
in space, including the final dictionary. It is probably faster than a loop, though, since the zip
, dict
, and slicing operators are written in C.
这篇关于将字符串列表转换成字典,以奇数索引的字符串作为键,以偶数索引的字符串作为值的Pythonic方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!