Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从位于字典中的列表中检索变量,位于列表中?二_Python - Fatal编程技术网

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

Python 如何从位于字典中的列表中检索变量,位于列表中?二,python,Python,好的,如果我有以下几点: fruits = [{ name:apple, color:[red,green], weight:1 }, { name:banana, color:[yellow,green], weight:1 }, { name:orange, color:orange, weight:[1,2] }] 因此,我需要编写一个程序,将获得重量和颜色的名称。 有人能告诉我怎么做吗 def findCarByC

好的,如果我有以下几点:

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

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

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)]

如果你对我在一行中如何做的符号方面感到困惑,你可以看看它是如何通过。如果你想要一个更简化的版本。您可以修改第一个方法(findit)以生成:

def findit3(fruits,color):
    mylist = []
    for indv in fruits:
        if color in indv['color']:
            mylist.append(  (indv['name'], indv['weight'])  )
    return mylist

所以,这不是一个“给我写些代码”的网站。。但我们很乐意帮助您编写自己的代码。你试过什么?你有什么特别的事吗?给我们看一些代码,问一些问题,你就会得到你需要的帮助。现在你已经发布了你尝试的功能,你需要告诉我们你想知道什么。你可以考虑告诉我们当你运行上面的代码时会发生什么,告诉我们你期望的输出。如果这是你正在使用的代码,你的键和值是不合适的——字符串没有被定义。你可能也想看看这个。如果有第二个字典和另一个数组呢?如果有另一个dict和数组呢?水果=[{'name':“apple”、'color':[“red”、“green”]、'weight':1}、{'name':“banana”、'color':[“yellow”、“green”]、'weight':“grange”]、'color':“orange”、'weight':[1,2]@biggerchadder水果列表中的区别在哪里?你的单子和我列的差不多。您是否希望通过分层比示例中显示的更多的列表和字典来增加复杂性?你能告诉我你需要解析什么吗?你在“there”中提到了第二本词典,但你能具体说明“there”吗?