如何从位于列表中的字典中的列表中检索变量? 2

问题描述:

好,所以如果我有以下几点:如何从位于列表中的字典中的列表中检索变量? 2

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") 
+2

这是功课吗? – srgerg

+6

SO真的不是一个“写我一些代码”的网站..但我们很乐意帮助您编写自己的代码。你有什么尝试?你坚持什么特别的东西?向我们展示一些代码,提出一些问题,并且您将获得所需的帮助。 – Levon

+0

one part,ill upload –

修正了示例词典。您还可以检查列表中是否存在字符串,而无需手动循环。

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 
+0

如果第二个字典和另一个数组在那里呢? –

+0

如果有另一个字典和一个数组,该怎么办?水果= [{ '名称': “苹果”, '颜色':[ “红”, “绿”], '体重':1 },{ '姓名': “香蕉”, “颜色':'yellow','green', 'weight':1 },{ 'name':'orange', 'color':'orange', 'weight':[1,2] }] –

+0

@thebiggerchadder水果列表中的区别在哪里?你的列表看起来与我所做的完全一样。您是否希望通过分层更多列表和词典来增加复杂度,而不是比示例中显示的更多?你能告诉我你需要解析什么吗?你在“there”中提到了第二个词典,但是你能指定“there”吗? – jakebird451