作为列表理解的一部分,将 str.split() 的结果存储到字典中的最佳方法是什么?

What is the best way to store the results of str.split() into a dictionary as part of a list comprehension?

给定以下示例数据:

values=['A 1','B 2','C 3']

我想创建一个字典,其中 A 映射到 1,B 映射到 2,C 映射到 3。以下工作正常,但有重复:

my_dict={value.split()[0]:value.split()[1] for value in values}

value.split() 的重复看起来很难看。有没有办法更优雅地创建字典而不重复value.split()?

我能想到的两种方式:

>>> {k:v for k,v in (s.split() for s in values)}
{'A': '1', 'B': '2', 'C': '3'}
>>> dict(s.split() for s in values)
{'A': '1', 'B': '2', 'C': '3'}

我建议阅读 dict 类型:https://docs.python.org/3/library/stdtypes.html#mapping-types-dict;特别是:

Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

以及在 PEP 274 中引入 dict-comprehensions:

The semantics of dict comprehensions can actually be demonstrated in stock Python 2.2, by passing a list comprehension to the built-in dictionary constructor:

>>> dict([(i, chr(65+i)) for i in range(4)])

is semantically equivalent to:

>>> {i : chr(65+i) for i in range(4)}

对于 functional 解决方案,您可以将 dictmapstr.split 一起使用:

values = ['A 1', 'B 2', 'C 3']

res = dict(map(str.split, values))

{'A': '1', 'B': '2', 'C': '3'}

你可以这样做 pythonic:

>>> values =['A 1','B 2','C 3']
>>> dict(map(str.split, values))
{'A': '1', 'C': '3', 'B': '2'}

str.split([sep[ maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

map(函数,可迭代的,...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

您可以看到字典没有按照您的列表排序。使用 collections.orderedDict 我们可以保留给定输入的顺序。

>>> import collections
>>> values =['A 1','B 2','C 3']
>>> my_ordered_dict = collections.OrderedDict(map(str.split, values))
>>> my_ordered_dict
OrderedDict([('A', '1'), ('B', '2'), ('C', '3')])