简体   繁体   中英

How do I convert a list to an integer?

This my code:

snumA = random.sample([4,8,3], 1)
snumB = random.sample([7,2,6], 1)
snumC = random.sample([1,5,9], 1)

sgnA = random.choice(['+','-','/','*'])
sgnB = random.choice(['+','-','/','*'])
sgnC = random.choice(['+','-','/','*'])

if sgnA == '-' :
    sum1 = snumA - bnumA
    print 'minus'
if sgnA == '/' :
    sum1 = snumA / bnumA
    print 'divide'

Whenever I run this code I get an error message telling me that my operands are lists and not integers. I've looked everywhere and I still don't know what to do. Could I have some help, please?

Change to :

snumA = random.choice([4,8,3])

which will give you an int instead of a list . To understand better the error here is that you try to use lists (cause random.sample returns a list type result) as integers to make arithmetic operations which is false. On the other hand random.choice does what you want but returns an int type result - so you won't get an error.

The problem is: snumA = random.sample([4,8,3], 1) returns a list of one element (for example: [3] ). What you can do instead is: Either use snumA = random.choice([4,8,3]) which returns directly an integer. Or you get hold of the first element of your list with snumA[0] or directly snumA = random.sample([4,8,3], 1)[0]

  1. As suggested before, use random.choice
  2. bnumA is not defined. The code below assumes you meant snumB

So the code you are looking for might be:

import random

snumA = random.choice([4,8,3])
snumB = random.choice([7,2,6])
snumC = random.choice([1,5,9])

operators = {'+':'Plus', '-':'Minus', '/':'Division','*':'Multiplication'}
sgnA = random.choice(list(operators.keys()))
sgnB = random.choice(list(operators.keys()))
sgnC = random.choice(list(operators.keys()))

print(eval(str(snumA)+sgnA+str(snumB)))
print(operators[sgnA])

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