如果我有以下购物商店的商品清单:
shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5},
{'item': 'banana', 'amount': 12, 'cost': 6},
{'item': 'strawberry', 'amount': 8, 'cost': 9}]
所以我在列表中有几个词。我想知道如何让项目知道该项目。例如:
def x(item)
#do something to get the dict
print dict
x('apple') #print {'item': 'apple', 'amount': 10, 'cost': 5}
x('banana') #print {'item': 'banana', 'amount': 12, 'cost': 6}
最短,最有效的方法是什么?
答案 0 :(得分:3)
如果您打算按'item'
查找条目,那么您应考虑使用dict
哪些密钥是'item'
而不是list
dict
}。
shop_list = {
'apple': {'amount': 10, 'cost': 5},
'banana': {'amount': 12, 'cost': 6},
'strawberry': {'amount': 8, 'cost': 9}
}
shop_list['banana'] # {'amount': 10, 'cost': 5}
特别是,这会使查找 O(1)而不是遍历list
所需的 O(n)。
如果您无法更新生成原始shop_list
的代码,则可以使用字典理解来转换已存在的数据。
formatted_shop_list = {product['item']: product for product in shop_list}
答案 1 :(得分:0)
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/application_7.xsd" version="7">
<display-name>VetSpaEAR</display-name>
<module>
<ejb>com.vetspa-VetSpaEJB-0.0.1-SNAPSHOT.jar</ejb>
</module>
<module>
<web>
<web-uri>com.vetspa-VetSpaWS-0.0.1-SNAPSHOT.war</web-uri>
<context-root>/VetSpaWS</context-root>
</web>
</module>
<module>
<web>
<web-uri>com.vetspa-VetSpaRS-0.0.1-SNAPSHOT.war</web-uri>
<context-root>/VetSpaRS</context-root>
</web>
</module>
<library-directory>lib</library-directory>
然后,您可以将此功能称为:
def x(shop_list, item): # remove first parameter if you want to use global variable
for i in shop_list:
if i['item'] == item:
return i
答案 2 :(得分:0)
您可以尝试遍历列表并只提取与您的商店项目匹配的字典:
def shop_item(shop_list, item):
return next((x for x in shop_list if x['item'] == item), None)
# or next(filter(lambda x: x['item'] == item, shop_list), None)
其工作原理如下:
>>> shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5},
... {'item': 'banana', 'amount': 12, 'cost': 6},
... {'item': 'strawberry', 'amount': 8, 'cost': 9}]
>>> shop_item(shop_list, 'apple')
{'item': 'apple', 'amount': 10, 'cost': 5}
>>> shop_item(shop_list, 'grape')
None
上面使用带有生成器表达式的next()
来迭代列表,直到满足条件,如果找不到item,则返回None
。
答案 3 :(得分:0)
您可以尝试以下方法:
def x(item):
return [elements for elements in shop_list if elements['item'] == item]
x('apple') #print {'item': 'apple', 'amount': 10, 'cost': 5}
x('banana') #print {'item': 'banana', 'amount': 12, 'cost': 6}
这将返回列表项(如果找到)
[{'amount': 12, 'cost': 6, 'item': 'banana'}]
,如果未找到结果,将返回empty list
。