Python字典:检查';类似';钥匙
假设我有一本字典,里面有一些键:值对。除了重新定义字典,还有什么方法可以检查某个东西是否与字典中的某个键相似 比如说Python字典:检查';类似';钥匙,python,dictionary,Python,Dictionary,假设我有一本字典,里面有一些键:值对。除了重新定义字典,还有什么方法可以检查某个东西是否与字典中的某个键相似 比如说 items = [ 'green apple', 'yellow pepper', 'green pepper', 'red pepper' ] fruitsandveggies = { 'apple': 2, 'banana': 5, 'pepper': 6} for item in items: if item is similar to some
items = [ 'green apple', 'yellow pepper', 'green pepper', 'red pepper' ]
fruitsandveggies = { 'apple': 2, 'banana': 5, 'pepper': 6}
for item in items:
if item is similar to some key in fruitsandveggies ('green apple' is similar to 'apple',
set qty = value of that key
then print that qty
为了澄清一些问题,我所说的相似只是在字符串中包含“key”。因此,“蟹状苹果”、“青苹果”、“华盛顿苹果”都包含“苹果”,这是其中的一个键。您可以使用它返回序列相似性的度量值,作为范围[0,1]
中的浮点值
和max
功能:
>>> fruitsandveggies = { 'apple': 2, 'banana': 5, 'pepper': 6}
>>> max(fruitsandveggies.items(),key=lambda (i,j):difflib.SequenceMatcher(None, i,'green apple').ratio())
('apple', 2)
如果您只想获取值,请使用简单的索引(
[1]
)如果我理解正确,我想这就是您想要做的:
import re
items = [ 'green apple', 'yellow pepper', 'green pepper', 'red pepper' ]
fruitsandveggies = { 'apple': 2, 'banana': 5, 'pepper': 6}
for key in fruitsandveggies.keys():
fruitsandveggies[key] = 0
for item in items:
if re.search(key, item): # if it finds the key string in the item
fruitsandveggies[key] += 1
#print str(fruitsandveggies[key]) + ' ' + key #python 2
print(str(fruitsandveggies[key]) + ' ' + key) #python 3
它会打印出来
3胡椒粉
一个苹果
0香蕉
在本例中我不知道您的问题是否正确,但以下是一种检查项目中类似于字典键的字符串的方法:
for i in items:
if any(key in i for key in fruitsandveggies.keys()):
print key # or print fruitsandveggies[key]
for key in fruitsandveggies:
if any(key in item for item in items):
qty = fruitsandveggies[key]
print(qty)
绿苹果和苹果有什么相似之处?如果是因为名字的缘故,那么松树苹果呢?定义相似的。如果
胡椒
类似于青椒
是否青椒
也类似于胡椒
?青椒和青苹果相似吗?orange
与orange pepper
相似吗?是的,但您必须更具体地说明什么是“相似的”。“蟹肉苹果”也算类似吗?“Manzana”(西班牙语代表苹果)算数吗?“Apple”或“aple”也算类似吗“Apple”或“Apple”怎么样“?另外,请注意,检查‘相似性’将严重影响词典的性能。一旦定义了相似性并为其实现了一个函数,测试相似性的唯一方法就是迭代每个键,这几乎与拥有字典的目的背道而驰。如果re.search(…)
调用保持如此简单,则可以执行打印(水果和蔬菜[key],key)
并避免所有类型转换,您可以将其替换为中的。否则,我认为您应该实现re.IGNORECASE
。