Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

convert a list[str] to list[int] in python

This is my code:

import os
from typing import Mapping

from colorama import Fore , init

init()

os.system("cls" or "clear")

clear = lambda: os.system('cls')
#GIVE A NUMBER
num = int(input(Fore.GREEN+"Please Enter A Number: "))
#GIVE A LIST NUMBER
listed = input(Fore.GREEN+"Please Enter A List Of Number: ")
# CONVERT INPUT(STR) TO LIST:
listed = [listed]
#CONVERT LIST(STR) TO LIST(INT)
listed= list(map(int, listed))
#APPEND NUMBER TO LIST:
listed.append(num)
#SORT LIST
listed = listed.sort()
#PRINT LIST
print(Fore.RED+listed)

and i got these error: Please Enter A Number: 12

Please Enter A List Of Number: 12,35,25

Traceback (most recent call last):

File "c:UsersAdministratorDesktop oya1.py", line 14, in

listed= list(map(int, listed))

ValueError: invalid literal for int() with base 10: '12,35,25'

What should i do to convert all number is in input to int????

question from:https://stackoverflow.com/questions/65872776/convert-a-liststr-to-listint-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's also an error in your last line. Here's the whole thing corrected:

import os
from typing import Mapping

from colorama import Fore , init

init()

os.system("cls" or "clear")

clear = lambda: os.system('cls')
#GIVE A NUMBER
num = int(input(Fore.GREEN+"Please Enter A Number: "))
#GIVE A LIST NUMBER
listed = input(Fore.GREEN+"Please Enter A List Of Number: ")
# CONVERT INPUT(STR) TO LIST:
listed = listed.split(',')
print(listed)
#CONVERT LIST(STR) TO LIST(INT)
listed= list(map(int, listed))
#APPEND NUMBER TO LIST:
listed.append(num)
#SORT LIST
listed = listed.sort()
#PRINT LIST
print(Fore.RED+str(listed))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...