什么是python';s相当于ruby';收集
在ruby中,您可以这样做以从哈希中收集重要值:什么是python';s相当于ruby';收集,python,Python,在ruby中,您可以这样做以从哈希中收集重要值: hash = {'a'=> {'consider_this' => 1, 'dont_consider_this' => 4}, 'b' => {'consider_this' => 4, 'dont_consider_this' => 4}} hash.collect{|key, value| value['consider_this']}=> [1, 4]
hash = {'a'=> {'consider_this' => 1, 'dont_consider_this' => 4},
'b' => {'consider_this' => 4, 'dont_consider_this' => 4}}
hash.collect{|key, value| value['consider_this']}=> [1, 4]
=> [1, 4]
试图在python中做同样的事情(这是一种新的语言),但没有成功 在字典的值上使用a:
nested = {
'a': {'consider_this': 1, 'dont_consider_this': 4},
'b': {'consider_this': 1, 'dont_consider_this': 4}
}
[v['consider_this'] for v in nested.values()]
外部字典中的键在这里并不重要。输出为[1,1]
,的所有值按任意顺序考虑此
键。另请参阅。如果考虑\u此
键缺失,则认为是错误
您可以使用筛选只考虑带有特定键的字典:
nested = {
'a': {'consider_this': 1, 'dont_consider_this': 4},
'b': {'consider_this': 2, 'dont_consider_this': 4},
'c': {'dont_consider_this': 4},
}
[v['consider_this'] for v in nested.values() if 'consider_this' in v]
# outputs [1, 2] or [2, 1]
或提供默认值:
nested = {
'a': {'consider_this': 1, 'dont_consider_this': 4},
'b': {'consider_this': 2, 'dont_consider_this': 4},
'c': {'dont_consider_this': 4},
}
[v.get('consider_this', 0) for v in nested.values()]
# [1, 2, 0], or alternative orders
后者使用的是
考虑使用{…}
(集合理解)而不是列表来反映排序在这里并不重要;结果将只保存唯一的值,因此{1}
如果所有都考虑此
键只有1
的值
python(新语言)在ruby中,您可以这样做来从散列中收集值 python与ruby的collect的等价物是什么 python中的等价物是:
d = {
'a': {'consider_this': 1, 'dont_consider_this': 'a'},
'b': {'consider_this': 4, 'dont_consider_this': 'b'},
'c': {'hello': 2}
}
results = []
for key, val in d.items():
x = val.get('consider_this', False)
results.append(x)
print results
--output:--
[1, False, 4]
当您获得更多的经验时,您可以学习如何使用所谓的列表理解来更有效地从循环创建列表
:
results = [
val.get('consider_this', False)
for key, val in d.items()
]
print results
--output:--
[1, False, 4]
请注意,在python中,您可以使用d.values()
而不是d.items()
,因为您不使用键:
results = [
val.get('consider_this', False)
for val in d.values()
]
print results
--output:--
[1, False, 4]
在ruby 1.9+中,哈希是有序的,但在python字典中是不有序的,因此,如果结果的顺序对您很重要,您可以使用python的OrderedDict:
import collections as coll
d = coll.OrderedDict(
[
('a', coll.OrderedDict([('consider_this', 1), ('dont_consider_this', 'a')])),
('b', coll.OrderedDict([('consider_this', 4), ('dont_consider_this', 'b')])),
('c', coll.OrderedDict([('hello', 2)]))
]
)
results = [
val.get('consider_this', False)
for key, val in d.items()
]
print results
--output:--
[1, 4, False]
你甚至有用Python构建的等效数据结构吗?你的代码生成的是
[1,1]
,而不是[1,4]
。当然,这是一个简单的@Ohappartuck,请包括你在问题中构建的字典。事实上,这个问题看起来好像你不知道自己在做什么。
import collections as coll
d = coll.OrderedDict(
[
('a', coll.OrderedDict([('consider_this', 1), ('dont_consider_this', 'a')])),
('b', coll.OrderedDict([('consider_this', 4), ('dont_consider_this', 'b')])),
('c', coll.OrderedDict([('hello', 2)]))
]
)
results = [
val.get('consider_this', False)
for key, val in d.items()
]
print results
--output:--
[1, 4, False]