Как получить доступ к элементу словаря в цикле?

#python-3.x #dictionary #element

#python-3.x #словарь #элемент

Вопрос:

Я пытаюсь создать модель, которая будет предсказывать значения таймера трафика, определенные в словаре. Та же проблема уже решена и смоделирована в 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 amp;amp; 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 amp; peak_hours is very_light:
                    time_ext=more_decrease
                elif queue_len is less amp; peak_hours is heavy_morn:
                    time_ext=decrease
                elif queue_len is less amp; peak_hours is medium:
                    time_ext=decrease
                elif queue_len is less amp; peak_hours is heavy_eve :
                    time_ext=decrease
                elif queue_len is less amp; peak_hours is light:
                    time_ext=more_decrease
                elif queue_len is medium amp; peak_hours is very_light:
                    time_ext=increase
                elif queue_len is medium amp; peak_hours is heavy_morn:
                    time_ext=increase
                elif queue_len is medium amp; peak_hours is medium:
                    time_ext=do_not_change
                elif queue_len is medium amp; peak_hours is heavy_eve:
                    time_ext=increase
                elif queue_len is medium amp; peak_hours is light:
                    time_ext=do_not_change
                elif queue_len is long amp; peak_hours is very_light:
                    time_ext=do_not_change
                elif queue_len is long amp; peak_hours is heavy_morn:
                    time_ext=more_increase
                elif queue_len is long amp; peak_hours is medium:
                    time_ext=increase
                elif queue_len is long amp; peak_hours is heavy_eve:
                    time_ext=more_increase
                else:
                    time_ext=increase
print(time_ext)
 

Он должен печатать значение временного расширения после получения входных данных из функции, но он не печатает то же самое. Пожалуйста, помогите, если кто-нибудь знает ошибку, которую я делаю.

Комментарии:

1. «Я получаю сообщение об ошибке ниже» Вы забыли добавить ошибку. Это SyntaxError: EOL while scanning string literal в строке 4?

2. ошибка @Goyo выглядит следующим образом: ошибка повышения значения («нецелочисленная остановка для randrange()») Ошибка значения: нецелочисленная остановка для randrange()

Ответ №1:

Для доступа к dict используются два метода:

  1. q_len['less']
  2. q_len.get('less','') . Второй аргумент по умолчанию в случае, если ключ «меньше» не существует

Комментарии:

1. Феликс Мартинес, я все еще получаю сообщение об ошибке после изменения кода. для i в iter. __getattribute__ в q_len: ошибка типа: аргумент типа ‘int’ не может быть повторен

2. его ошибка выброса ниже в этой строке: трафик def (q_len, peak_hours): для i в iter. __getattribute__ в q_len: для j в iter. __getattribute__ в peak_hours: если q_len[‘меньше’] и peak_hours[‘очень легкий’]: timer=time_ext[‘больше_убывания’] если q_len[‘меньше’] и peak_hours[‘тяжелый_мор]: timer=time_ext[‘уменьшение’]

Ответ №2:

Ваша ошибка заключается в том, что randrange принимает только целочисленные (целочисленные) значения. Все дело в том, что он принимает случайные значения из a range , который опять же поддерживает только целые числа. Так, например random.randrange(0, 7.5) , не будет работать, потому 7.5 что не является целым числом (в нем есть десятичное число). Если вам нужно случайное число от 0 до 7.5 по 0.1 шагам, вы можете просто сделать random.randrange(0, 75)/10 это.