如何在循环中访问字典的元素?

How to access element of a dictionary in the loop?

我正在尝试制作一个模型来预测字典中定义的交通计时器的值。同样的问题已经在 MATLAB 中完成并模拟,但是我在 python 中访问字典中的元素时出现以下错误。

import random
q_len = {'less': random.randrange(0,8), 'medium': random.randrange(6,14), 
'long':random.randrange(12,30)}
peak_hours = {'very_light':random.randrange(0, 7.5), 'heavy_ 
 morn':random.randrange(7,11.5), 'medium':random.randrange(11,16.5), 
'heavy_eve':random.randrange(16,20.5), 'light':random.randrange(20,24.5)}
time_ext = {'more_decrease':random.randrange(-32 -8), 
'decrease':random.randrange(-16 -1), 'do_not_change':random.randrange(-8 
-0.5), 'increase':random.randrange(0, 16), 
'more_increase':random.randrange(8, 32)}
def traffic(queue_len, peak_hours):
#entry1 = float(input('Enter the value of length of queue: '))
#entry2 = float(input('Enter the value of peak_hr: '))
#if entry1 in q_len && entry2 in peak_hours:
        for i in iter.items in q_len:
            for j in iter.items in peak_hours:
                if queue_len is less & peak_hours is very_light:
                    time_ext=more_decrease
                elif queue_len is less & peak_hours is heavy_morn:
                    time_ext=decrease
                elif queue_len is less & peak_hours is medium:
                    time_ext=decrease
                elif queue_len is less & peak_hours is heavy_eve :
                    time_ext=decrease
                elif queue_len is less & peak_hours is light:
                    time_ext=more_decrease
                elif queue_len is medium & peak_hours is very_light:
                    time_ext=increase
                elif queue_len is medium & peak_hours is heavy_morn:
                    time_ext=increase
                elif queue_len is medium & peak_hours is medium:
                    time_ext=do_not_change
                elif queue_len is medium & peak_hours is heavy_eve:
                    time_ext=increase
                elif queue_len is medium & peak_hours is light:
                    time_ext=do_not_change
                elif queue_len is long & peak_hours is very_light:
                    time_ext=do_not_change
                elif queue_len is long & peak_hours is heavy_morn:
                    time_ext=more_increase
                elif queue_len is long & peak_hours is medium:
                    time_ext=increase
                elif queue_len is long & peak_hours is heavy_eve:
                    time_ext=more_increase
                else:
                    time_ext=increase
print(time_ext)

它应该在从函数中获取输入后打印时间延长的值,但它并没有打印相同的值。如果有人知道我正在做的错误,请帮助。

访问字典,两种方法:

  1. q_len['less']
  2. q_len.get('less','')。第二个参数是默认值,以防键 'less' 不存在

您的错误是因为 randrange 只接受整数(整数)值。重点是它从 range 中获取随机值,它同样只支持整数。因此,例如 random.randrange(0, 7.5) 不会起作用,因为 7.5 不是整数(它有一个小数)。如果你想要一个从 07.5 的随机数,步骤 0.1,你可以只做 random.randrange(0, 75)/10