如何一次遍历两个字典,并使用两个字典中的值和键获得结果

2024-05-13 23:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

def GetSale():#calculates expected sale value and returns info on the stock with              highest expected sale value
      global Prices
      global Exposure
      global cprice
      global bprice
      global risk
      global shares
      global current_highest_sale
      best_stock=' '
      for value in Prices.values():
          cprice=value[1]
          bprice=value[0]
          for keys, values in Exposure.items():
             risk=values[0]
             shares=values[1]
             Expected_sale_value=( (cprice - bprice ) - risk * cprice) * shares
             print (Expected_sale_value)
             if current_highest_sale < Expected_sale_value:
                current_highest_sale=Expected_sale_value
                best_stock=Exposure[keys]
     return best_stock +" has the highest expected sale value"

以上是我目前的代码。但出于某种原因,它似乎在做第一个循环,然后是第二个,然后是第二个,然后是第一个,然后是第二个。在返回第一个for循环之前,它每次到达第二个循环时似乎都会执行第二个循环。正因为如此,我得到的答案是不正确的。


Tags: valuestocksalecurrentglobalexposurebestexpected
3条回答

这个问题有点含糊,但回答标题时,可以同时获得键和值,如下所示:

>>> d = {'a':5, 'b':6, 'c': 3}
>>> d2 = {'a':6, 'b':7, 'c': 3}
>>> for (k,v), (k2,v2) in zip(d.items(), d2.items()):
    print k, v
    print k2, v2


a 5
a 6
c 3
c 3
b 6
b 7

不过,别介意字典里的钥匙是没有顺序的。此外,如果这两个字典不包含相同数量的键,则上面的代码将失败。

考虑到您的问题,我建议您创建一个生成器表达式,该表达式成对导航两个字典,并使用带自定义键的max来计算要计算的销售价格expected_sale_price和相应的库存

样本数据

Prices = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))
Exposure = dict(zip(range(10), ((randint(1,100), randint(1,100)) for _ in range(10))))

示例代码

def GetSale(Prices, Exposure):
    '''Get Sale does not need any globals if you pass the necessary variables as
       parameteres
    '''
    from itertools import izip
    def sale_price(args):
        '''
        Custom Key, used with the max function
        '''
        key, (bprice, cprice), (risk, shares) = args
        return ( (cprice - bprice ) - risk * cprice) * shares

    #Generator Function to traverse the dict in pairs
    #Each item is of the format (key, (bprice, cprice), (risk, shares))
    Price_Exposure = izip(Prices.keys(), Prices.values(), Exposure.values())


    #Expected sale price using `max` with custom key
    expected_sale_price = max(Price_Exposure, key = sale_price)
    key, (bprice, cprice), (risk, shares) =  expected_sale_price
    #The best stock is the key in the expected_sale_Price
    return "Stock {} with values bprice={}, cprice = {}, risk={} and shares={} has the highest expected sale value".format(key, bprice, cprice, risk, shares)

这个问题没有很好地定义,而且对于某些词典来说,接受的答案将失败。它依赖于密钥排序,这是不保证的。向字典中添加其他键、删除键,甚至添加键的顺序都会影响排序。

更安全的解决方案是选择一个字典,d在本例中,从中获取密钥,然后使用这些密钥访问第二个字典:

d = {'a':5, 'b':6, 'c': 3}
d2 = {'a':6, 'b':7, 'c': 3}
[(k, d2[k], v) for k, v in d.items()]

结果:

[('b', 7, 6), ('a', 6, 5), ('c', 3, 3)]

这并不比其他答案更复杂,而且对于访问哪些键是明确的。如果字典有不同的键顺序,比如d2 = {'x': 3, 'b':7, 'c': 3, 'a':9},那么仍然会给出一致的结果。

相关问题 更多 >