迭代元组列表和字典到m

2024-05-06 01:08:35 发布

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

Python新手-有没有一种简单的方法来迭代一个元组列表并使用性能阈值(即,每日销售额超出/低于预算销售额的百分比)进行计算?请参见以下信息:

daily_sales = [('A',150000),('B',73000),('C',110000),('D',231000),('E',66000)] 
budgeted_sales = {'A':140000,'B':103000,'C':80000,'D':20000,'E':90000}
performance_threshold = .20

Tags: 方法信息列表thresholdperformance阈值daily元组
3条回答

由于您是Python新手,这里有一个简单的方法可以做到这一点,而不需要太复杂的语法:

# For each tuple inside daily_sales
for sale in daily_sales:
  # Use the first element of that tuple as a key and check if it's inside the dictionary budgeted_sales
  if sale[0] in budgeted_sales:
    # Compare the value stored for that key with the second element of the tuple (which contains the other price) and print stuff
    if budgeted_sales[sale[0]] > sale[1]: print('Over')
    else: print('Under')

上面的检查是可选的,但是它确保您不会用不存在的键直接访问字典,然后尝试用存在的值添加不存在的值。你知道吗

我猜你要找的是这样的东西:

for i in daily_sales:
    if i[1] > budgeted_sales['A']:
    //Do something

这里最重要的一点是元组是不可变的,因此可以通过引用一个位置(例如i[0])来访问元组。Dict条目可以通过引用它们的键来访问(例如myDict['myKey']

我希望这有帮助!你知道吗

为了使事情简单化,你可以循环进行。第一行循环遍历daily_sales中的每个元组对。对于第一对,item[1]是150000。然后从字典中获取item[0](即A)。请注意,如果字典中没有匹配项,则此操作将失败。你知道吗

for item in daily_sales:
    performance = item[1] / float(budgeted_sales.get(item[0])) - 1
    if performance > 0:
        print "Over {0:.2%}".format(performance)
    else:
        print "Under {0:.2%}".format(performance)

Over 7.14%
Under -29.13%
Over 37.50%
Over 1055.00%
Under -26.67%

相关问题 更多 >