简体   繁体   中英

How do I convert a list of integers to ints?

I'm making a program to sort numbers from lowest to highest as long as the numbers are under 300, but I can't figure out how to change the user input into a list. Here's my code:

List1=[]
List2=[]
var=1
thing=input("Insert numbers here")
List1.append(thing)
while var < 300:
    for that in List1:
        if that < var:
            List2.append(number)
    var = var + 1
print(List2)

When I run the code, it says that in the 8th line, a string can't be compared with an int. Please help. Thanks in advance.

It looks like your variable that is a string. This is why you can't compare it against an integer. If you need to convert your string to an int you can simply wrap it with int (your_variable_here).

For example

if int(that) < var:

This would convert the string that to an integers (number). The benefits of converting it to a integer is that you can compare it against other integers, and use basic arithmetic operations . That wouldn't be possible if you used a string.

An even better solution would be to directly store the input as an integer.

List1.append(int(thing)) # We wrap the keyboard input with int

Also, if you are running Python 2.x I would recommend that you use raw_input , instead of input .

Since this doesn't seem to be in any loop, I don't see how you can have more than one entry in the list.. Perhaps you could have space seperated numbers entered? Using python 3 , this could be minimized like so (minus error handling):

nums = [x for x in list(map(int, input("Enter numbers: ").split())) if x < 300]    
nums.sort()

Or..

nums = input("Enter numbers: ") # Get the number string
nums = nums.split() # Split the string by space character
nums = list(map(int, nums)) # call int() on each item in the list, converting to int
nums.sort() # sort the list of numbers
nums = [x for x in nums if x < 300] # remove any numbers 300 or over.

Input/output:

Enter numbers: 1 5 301 3000 2
[1, 2, 5]

If you enter the numbers separated by commas, the following single line will work:

>>> sorted(list(input("Enter numbers: ")), reverse=True)
Enter numbers: 1, 2, 3
[3, 2, 1]

To remove numbers < 300:

>>> sorted([num for num in input("Enter numbers: ") if num < 300], reverse=True)
Enter numbers: 1, 301, 299, 300, 2, 3
[299, 3, 2, 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