Skip to main content
 首页 » 编程设计

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

2025年05月04日10Terrylee

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

[  {'file': 'test.py', 'revs': [181449, 181447]},  
{'file': 'test2.py', 'revs': [4321, 1234]}  ] 

请您参考如下方法:

可以只使用 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'] 

如果不使用 for 这个词,您可以使用:

>>> from operator import itemgetter 
>>> map(itemgetter('file'), d) 
['test.py', 'test2.py'] 

或者,没有导入:

>>> map(lambda L: L['file'], d) 
['test.py', 'test2.py']