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

标签 python dictionary

我有一个包含两个词典的列表。获取 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']

关于Python:有没有办法从列表中获取多个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444196/

相关文章:

python - 解析列表中的 Python 字典

java - 在 java 中使用 HashMap 的主要好处是什么?

c# - 在 C# 中从字典中过滤键值

python - 如何创建 python selenium 应用程序及其驱动程序?

python - 为什么不同时区的UTC时间不同?

python - 根据当前日期添加和计算行的非零值

python - 比较字典中的键和值,并将不匹配的值输出到列表中

c# - 使用 linq 将字典值转换为列表

python - dataclasses.Field 不将类型注释解析为实际类型

python - 如何让反斜杠符号显示出来?