我必须编写一个程序来计算给定列表中的水果数量。
我已经尝试了一个for循环,但没有任何成功。我也尝试过Counter,但这会删除第二个'banana',并且只能识别一个。
c = { 'banana': 'fruit', 'apple': 'fruit', 'pizza': 'fastfood', 'fries': 'fastfood' }
v = [ 'fries', 'banana', 'banana', 'apple', 'pizza' ]
r = len([v for v in c if c.items() == 'fruit' in c.value()])
print(r)我原以为这会给出水果的数量,但是,我得到的输出是0。
发布于 2019-01-15 01:04:15
你可以从所有的水果中构造一个集合并使用它:
c = { 'banana': 'fruit', 'apple': 'fruit', 'pizza': 'fastfood', 'fries': 'fastfood' }
# collect all fruits into a set that only contains fruit
fixed = set(k for k,v in c.items() if v=="fruit") # cheating by creating the set in setup ;)
v = [ 'fries', 'banana', 'banana', 'apple', 'pizza' ]
r = sum(f in fixed for f in v)
print(r)返回3-因为True ( O(1)集合查找的结果)等于1,而False等于0。
在大多数情况下,这种解决方案比Daniel Trugman's solution更差,在其他情况下,它会稍微快一些:
考虑一下:
c = {'banana':'fruit'}
v = ['banana' * 100000]
fixed = set(k for k,v in c.items() if v=="fruit")字典理解直接访问c['banana']的值100000次,并做100000次c[val] == 'fruit'来检查它是否是水果。这比在构造的集合上检查100000倍的'banana' in fixed要慢。
对于手边的例子,dict comp是很好的。
大多数情况下,dict-comp速度更快:
setup_code = """
c = { 'banana': 'fruit', 'apple': 'fruit', 'pizza': 'fastfood', 'fries': 'fastfood' }
v = [ 'fries', 'banana', 'banana', 'apple', 'pizza' ]
fixed = set(k for k,v in c.items() if v=="fruit")
"""
setup_code2 = """
c = { 'banana': 'fruit', 'apple': 'fruit', 'pizza': 'fastfood', 'fries': 'fastfood' }
v = ['banana']*1000
fixed = set(k for k,v in c.items() if v=="fruit")
"""
using_set = """
# collect all fruits into a set that only contains fruit
r = sum(1 if f in fixed else 0 for f in v)
"""
using_dict_comp = """
r = sum(1 for val in v if c[val] == 'fruit')
"""
import timeit
print("set:", timeit.timeit(using_set,setup=setup_code,number=10000))
print("dict:", timeit.timeit(using_dict_comp,setup=setup_code,number=1000))
print("set:", timeit.timeit(using_set,setup=setup_code2,number=10000))
print("dict:", timeit.timeit(using_dict_comp,setup=setup_code2,number=10000))输出:
'set:', 0.0069959163665771484
'dict:', 0.0006661415100097656
'set:', 0.6653687953948975 # this "fasteness" goes away as soon as more items are in the set
'dict:', 0.7533159255981445 发布于 2019-01-15 01:08:53
试试看:
r = sum(1 for val in v if c[val] == 'fruit')或者,就像@jpp建议的那样(略短一点):
r = sum(c[val] == 'fruit' for val in v)或者,如果你需要速度,就像@Patrick Artner:
ctag = { k: v for k, v in c.items() if v == 'fruit' }
r = sum(1 for val in v if val in ctag)解释:每次访问并比较这个值是相当昂贵的。创建一个新的字典,其中所有的键都是水果,然后简单地忽略这些值,这样的成本更低。这比使用集合更好,因为集合是使用平衡树实现的,搜索复杂度为O(logN),而字典是使用哈希图实现的,搜索复杂度为O(1),只要映射中的项目数量不超过内部容量太多...
发布于 2019-01-15 01:02:24
首先尝试这个数字类型,然后查找字典c的键的匹配项
c = { 'banana': 'fruit', 'apple': 'fruit', 'pizza': 'fastfood', 'fries':'fastfood' }
v = [ 'fries', 'banana', 'banana', 'apple', 'pizza' ]
result = [c[i] for i in v] #this will iterate and give the type of element
output={}
for key in c.values(): output[key] =str(result.count(key))
print(output)
https://stackoverflow.com/questions/54185885
复制相似问题