简体   繁体   中英

typeerror for mathematical operations and comparison operator

There is a part in my code wherein I have to use math operations and comparison operators.

For example:

avail_res = [4, 2] # avail_res[0] gives me int
r_select_act = [2] # list
score = [2, 4, 0, 6] # list

The code I am thinking is something like this:

avail_res[0] = avail_res[0] - r_select_act
avail_res[0] = avail_res[0] + r_select_act

Moreover, there is a conditional statement in my code that goes like this:

for num in score: # num gives int type
    if num <= avail_res[0] and num != 0:

Any help/suggestion to get rid of this error?

Traceback (most recent call last):
    avail_res[0] = avail_res[0] - r_select_act
TypeError: unsupported operand type(s) for -: 'int' and 'list'

Thank you. I tried getting the type of the different values. (see comment)

EDIT: r_select_act can have more than one value or none at all. for example, r_select_act = [2, 3], therefore all I have to do is to subtract avail_res[0] with both 2 and 3. Moreover if r_select_act is null, this should give me a zero value for r_select_act. Therefore, avail_res[0] = avail_res[0] - 0.

This message

Traceback (most recent call last):
    avail_res[0] = avail_res[0] - r_select_act
TypeError: unsupported operand type(s) for -: 'int' and 'list'

says that this is an int:

avail_res[0]

this this is a list:

r_select_act

and that the minus operator is not defined on int - list .

The minus operator is defined on int - int , so perhaps you want to extract an element from the list?

avail_res[0] = avail_res[0] - r_select_act[0]

From what I understood in the question,

avail_res = [4, 2]
r_select_act = [2, 3]
score = [2, 4, 0, 6]

# new code from here

# create a new list calculations to hold all the subtractions.
calculation = []

# condition to check if r_select_act is not empty
if len(r_select_act) != 0:
    # loop through all values in r_select_act
    for i in r_select_act:
        # substract avail_res[0] with each value in r_select_act and append it to calculations.
        calculation.append(avail_res[0] - i)

# if r_select_act is empty then calculation equals avail_res
else:
    calculation = avail_res

print(calculation)

If you print out calculation it will hold the values [2,1] because 4-2=2 and 4-3=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM