我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
我有一个字典列表,像这样:
[{'value': 'apple', 'blah': 2},
{'value': 'banana', 'blah': 3} ,
{'value': 'cars', 'blah': 4}]
我想要['苹果','香蕉','汽车']
做这件事最好的方法是什么?
当前回答
我想简单如下就能给你你想要的。
In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']
你也可以通过map和lambda的组合来做到这一点,但是列表理解看起来更优雅,更python化。
对于一个较小的输入列表,理解是要走的路,但如果输入真的很大,那么我猜生成器是理想的方式。
In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'
这里是对所有可能的更大投入的解决方案的比较
In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
...: for i in l:
...: yield i.get('value', None)
...:
In[4]: def list_comp_verison():
...: return [i.get('value', None) for i in l]
...:
In[5]: def list_verison():
...: ll = []
...: for i in l:
...: ll.append(i.get('value', None))
...: return ll
In[10]: def map_lambda_version():
...: m = map(lambda i:i.get('value', None), l)
...: return m
...:
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
正如你所看到的,生成器是一个比其他更好的解决方案,map也比生成器慢,原因我将留给OP来解决。
其他回答
一个非常简单的方法是:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
输出:
['apple', 'banana', 'cars']
假设每个字典都有一个值键,你可以这样写(假设你的列表名为l)
[d['value'] for d in l]
如果价值可能丢失,您可以使用
[d['value'] for d in l if 'value' in d]
对于这样一个非常简单的例子,理解伊斯梅尔·巴达维的答案绝对是正确的。
但是,当事情变得更加复杂,并且需要开始编写包含复杂表达式的多子句或嵌套推导时,就值得考虑其他替代方案了。有几种不同的(准)标准方法可以在嵌套的字典和列表结构上指定xpath样式的搜索,例如JSONPath、DPath和KVC。在PyPI上有很好的库供他们使用。
下面是一个名为dpath的库的示例,展示了它如何简化一些更复杂的东西:
>>> dd = {
... 'fruits': [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3}],
... 'vehicles': [{'value': 'cars', 'blah':4}]}
>>> {key: [{'value': d['value']} for d in value] for key, value in dd.items()}
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
>>> dpath.util.search(dd, '*/*/value')
{'fruits': [{'value': 'apple'}, {'value': 'banana'}],
'vehicles': [{'value': 'cars'}]}
或者,使用jsonpath-ng:
>>> [d['value'] for key, value in dd.items() for d in value]
['apple', 'banana', 'cars']
>>> [m.value for m in jsonpath_ng.parse('*.[*].value').find(dd)]
['apple', 'banana', 'cars']
乍一看,这一点可能不那么简单,因为find返回匹配对象,其中除了匹配值之外还包括各种内容,比如直接指向每个项的路径。但是对于更复杂的表达式,能够指定像'*.[*]这样的路径。Value '而不是每个*的理解子句会产生很大的不同。此外,JSONPath是一种语言不可知的规范,甚至有在线测试人员可以非常方便地进行调试。
遵循这个例子——
songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]
print("===========================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')
playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')
# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))
我想简单如下就能给你你想要的。
In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']
你也可以通过map和lambda的组合来做到这一点,但是列表理解看起来更优雅,更python化。
对于一个较小的输入列表,理解是要走的路,但如果输入真的很大,那么我猜生成器是理想的方式。
In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'
这里是对所有可能的更大投入的解决方案的比较
In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
...: for i in l:
...: yield i.get('value', None)
...:
In[4]: def list_comp_verison():
...: return [i.get('value', None) for i in l]
...:
In[5]: def list_verison():
...: ll = []
...: for i in l:
...: ll.append(i.get('value', None))
...: return ll
In[10]: def map_lambda_version():
...: m = map(lambda i:i.get('value', None), l)
...: return m
...:
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
正如你所看到的,生成器是一个比其他更好的解决方案,map也比生成器慢,原因我将留给OP来解决。