简体   繁体   中英

Take numbers from an unsorted string and convert them to a list with each number separated by a comma

I have an input:

L1 = input()

I want the output to be:

[1, 7, -3, 10, 42, 5, 0, 17]

The input is "1 7 -3 10 42 5 0 17" which means that when I print L1, it yields:

1 7 -3 10 42 5 0 17

Using inp(input()) gives me "Invalid literal for int() with base 10:". Using .split does not change the output.

If I get the user input as a list, then it yields:

[1 7 -3 10 42 5 0 17]

The string of numbers cannot be inputted individually, it must be inputted as a whole and then "split" with a comma. However;

L1 = input()
L1.split() or L1.split(",")
print(L1)

just yields...

1 7 -3 10 42 5 0 17

In order for L1 to be updated properly, you have to assign it the value that L1.split() returns.

L1 = "1 7 -3 10"
L1 = L1.split()
print(L1)

Output: ['1', '7', '-3', '10']

Or if you want a list of integers:

L1 = "1 7 -3 10"
L1 = [int(i) for i in L1.split()]
print(L1)

Output: [1, 7, -3, 10]

If you want to split by space or comma, you should use regexp splitting. Also, the split items are type str and you probably want to convert them to type int .

Here's the code:

import re
L1 = input()
L1 = [int(i) for i in re.split('[\s,]+', L1) if i]
print(L1)

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