0

私が次のものを持っていれば大丈夫です:

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

1 に答える 1

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)

この関数は 1 つのインスタンスのみを返します。たとえば、緑が表示されるすべてのインスタンスを見つける必要がある場合は、次の 2 番目の関数が機能します。

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

1行でそれを行った方法の表記上の側面に混乱している場合は、pythons docs hereを介してどのように行われるかを確認できます。より単純化されたバージョンが必要な場合。最初のメソッド (find) を変更して、次の結果を得ることができます。

def findit3(fruits,color):
    mylist = []
    for indv in fruits:
        if color in indv['color']:
            mylist.append(  (indv['name'], indv['weight'])  )
    return mylist
于 2012-06-07T01:46:47.250 に答える