好的,如果我有以下内容:
fruits = [{
name:apple,
color:[red,green],
weight:1
}, {
name:banana,
color:[yellow,green],
weight:1
}, {
name:orange,
color:orange,
weight:[1,2]
}]
所以我需要编写一个程序,通过颜色获得权重和名称。 有人可以告诉我该怎么做。
def findCarByColor(theColor):
z=0
for i in carList:
for a,b in i.iteritems():
#print a,"a", b, "b"
for d in b:
#print d
if d is theColor:
print carList [0][b][0]
return z
print findCarByColor("Red")
答案 0 :(得分:2)
修复了示例字典。您还可以检查列表中是否存在字符串,而无需手动循环。
fruits = [{
'name':"apple",
'color':["red","green"],
'weight':1
}, {
'name':"banana",
'color':["yellow","green"],
'weight':1
}, {
'name':"orange",
'color':"orange",
'weight':[1,2]
}]
def findit(fruits,color):
for indv in fruits:
if color in indv['color']:
return indv['name'], indv['weight']
print findit(fruits,"red")
结果:('apple', 1)
此函数仅返回一个实例。如果您需要找到例如绿色的每个实例,则第二个函数将起作用:
def findit2(fruits,color):
return [(x['name'],x['weight']) for x in fruits if color in x['color']]
print findit2(fruits,"green")
结果将是:[('apple', 1), ('banana', 1)]
如果您对我在一行中如何做到的符号方面感到困惑,您可以通过pythons docs here了解它是如何完成的。如果你想要一个更简化的版本。您可以修改第一个方法(findit)以产生:
def findit3(fruits,color):
mylist = []
for indv in fruits:
if color in indv['color']:
mylist.append( (indv['name'], indv['weight']) )
return mylist