a=['1','2','3','4','5'] #The integer represented as a string in this listb=[] #Fresh listfor i in a: #Declaring variable (i) as an item in the list (a).b.append(int(i)) #Look below for explanationprint(b)
def maybeMakeNumber(s):"""Returns a string 's' into a integer if possible, a float if needed orreturns it as is."""
# handle None, "", 0if not s:return stry:f = float(s)i = int(f)return i if f == i else fexcept ValueError:return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))print(converted)
from collections.abc import Iterable, Mapping
def convertEr(iterab):"""Tries to convert an iterable to list of floats, ints or the original thingfrom the iterable. Converts any iterable (tuple,set, ...) to itself in output.Does not work for Mappings - you would need to check abc.Mapping and handlethings like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):return iterab
if isinstance(iterab, Iterable):return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)print(converted)
# Python3 code to demonstrate# converting list of strings to int# using naive method
# initializing listtest_list = ['1', '4', '3', '6', '7']
# Printing original listprint ("Original list is : " + str(test_list))
# using naive method to# perform conversionfor i in range(0, len(test_list)):test_list[i] = int(test_list[i])
# Printing modified listprint ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']Modified list is : [1, 4, 3, 6, 7]
方法#2:使用列表理解
# Python3 code to demonstrate# converting list of strings to int# using list comprehension
# initializing listtest_list = ['1', '4', '3', '6', '7']
# Printing original listprint ("Original list is : " + str(test_list))
# using list comprehension to# perform conversiontest_list = [int(i) for i in test_list]
# Printing modified listprint ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']Modified list is : [1, 4, 3, 6, 7]
方法#3:使用map()
# Python3 code to demonstrate# converting list of strings to int# using map()
# initializing listtest_list = ['1', '4', '3', '6', '7']
# Printing original listprint ("Original list is : " + str(test_list))
# using map() to# perform conversiontest_list = list(map(int, test_list))
# Printing modified listprint ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']Modified list is : [1, 4, 3, 6, 7]