Python:有没有办法从列表中获取多个项目?

ima*_*hat 1 python dictionary

我有一个包含两个词典的列表.获取test.py和test2.py并将它们作为列表[test.py,test2.py]的最简单方法是什么?如果可能的话,我想在没有for循环的情况下这样做.

[  {'file': 'test.py', 'revs': [181449, 181447]}, 
{'file': 'test2.py', 'revs': [4321, 1234]}  ]
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 8

可以只使用一个list comp- 这是一种for循环我想:

>>> d = [  {'file': 'test.py', 'revs': [181449, 181447]}, 
{'file': 'test2.py', 'revs': [4321, 1234]}  ]
>>> [el['file'] for el in d]
['test.py', 'test2.py']
Run Code Online (Sandbox Code Playgroud)

不使用这个词for,你可以使用:

>>> from operator import itemgetter
>>> map(itemgetter('file'), d)
['test.py', 'test2.py']
Run Code Online (Sandbox Code Playgroud)

或者,没有导入:

>>> map(lambda L: L['file'], d)
['test.py', 'test2.py']
Run Code Online (Sandbox Code Playgroud)

  • +1,但是输入它的速度比我快.;) (3认同)