Home > Net >  Type error: Comparing an Integer and List in For Loop
Type error: Comparing an Integer and List in For Loop

Time:06-14

Python beginner here. How can you solve comparing list and int error in for loop of a dictionary, please help!

from random import *
passenger = list(range(1,51))

timelist = []
for i in range(1,51):
    n = randint(15,51)
    timelist.append(n)
    
passenger_time = {'passenger':passenger, 'timelist':timelist}

for x in passenger_time.values():
    if 40 > x > 15:
        print('passenger {} accepted'.format(y))
    else:
        print('not accepted')

CodePudding user response:

X is a list. As of right now, you are comparing, for instance, [1, 2, 3, 4, 5], to integers, in this case, 40 and 15.

You will have to access each element of the list. I'm not positive what you're trying to do with this code, however, what I've put below is an example of accessing each key in the list.

for x in passenger_time.values():
    y = passenger_time[x]

    if 40 > y > 15:
      print('passenger {} accepted'.format(y))
    else:
      print('not accepted')

CodePudding user response:

I suspect what you want is:

for pass, time in zip(passenger_times['passenger'], passenger_times['timelist']):
    if 15 < time < 40:
        print(f'passenger {pass} is accepted')

This iterates over the two lists in parallel. It checks the value in one of the lists, then prints the corresponding value from the other list.

Your code is just iterating over the two values in the dictionary. The first time, x contains the entire passenger list, the second time it contains the entire timelis list. It makes no sense to do 15 < x < 40 when x is a list.

CodePudding user response:

Can you please explain a little more what you're trying to do (what you're trying to compare)?

*and write your if like this:

if (x < 40) and (x > 15):
    ...

It might work in python, the way you wrote it, but you're definately going to have a problem if you're gonna use other languages

  • Related