Python:比较列表无法打印

时间:2013-12-29 01:50:25

标签: python

不打印&&不给错误,为什么?

#!/usr/bin/python
prices = {"banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3}
stock = {"banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15}

for item in set(prices) & set(stock):
    if prices[item] == stock[item]:
        print item
        print "price: " + str(prices[item])
        print "stock: " + str(stock[item])

2 个答案:

答案 0 :(得分:2)

您正在比较每个共享密钥的值,但这些值都不相等:

>>> for item in set(prices) & set(stock):
...     print '{:6}: {:3} == {:2} = {}'.format(item, prices[item], stock[item], prices[item] == stock[item])
... 
orange: 1.5 == 32 = False
pear  : 3   == 15 = False
banana: 4   == 6  = False
apple : 2   == 0  = False

条件prices[item] == stock[item]永远不会为真。

答案 1 :(得分:1)

因为在这:

set(prices) & set(stock)

您正在进行交叉,您将获得pricesstock之间的所有常用项目(无需再次检查),因此您可能只想打印它:

for item in set(prices) & set(stock):
        print item
        print "price: " + str(prices[item])
        print "stock: " + str(stock[item])

<强>输出:

orange
price: 1.5
stock: 32

pear
price: 3
stock: 15

banana
price: 4
stock: 6

apple
price: 2
stock: 0

PS:我假设这是OP所期望的。