在python中,我们使用列表来存储不同的元素。在这篇文章中,我们将讨论将字符串列表转换为ints的不同方法。我们还将讨论如何在 python 中把一个字符串列表转换为 ints。
目录
- int()函数
- isdigit()方法
- 在Python中使用for循环将字符串列表转换为Ints
- 使用List Comprehension将字符串列表转换为整数
- 使用map()函数将字符串列表转换为Ints
- 使用eval()函数将字符串列表转换为Ints
- 在Python中把字符串列表转换为Ints。
- 在Python中把字符串列表转换为Ints格式。
- 总结
int()函数
int() 函数接收一个字符串或浮点符号作为其输入参数,并返回一个整数,如下所示。
myStr = "11"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))
输出。
data type of 11 is <class 'str'>
data type of 11 is <class 'int'>
如果int() 函数的输入不能被转换为整数,程序会遇到一个ValueError 异常,并以""结束。[ValueError: invalid literal for int() with base 10](ValueError: invalid literal for int() with base 10)".你可以在下面的例子中观察到这一点。
myStr = "Aditya"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))
输出。
data type of Aditya is <class 'str'>
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myInt = int(myStr)
ValueError: invalid literal for int() with base 10: 'Aditya'
为了避免出现异常,我们可以先检查输入的数据是否可以转换为整数。浮点数总是会被转换为整数。然而,当int() 函数的输入是一个字符串,并且由数字以外的字符组成时,就会出现ValueError 异常。因此,要将一个字符串转换为整数,我们首先要检查它是否只由数字组成。为此,我们将使用isdigit() 方法。
isdigit()方法
isdigit() 方法,当对一个字符串调用时,如果该字符串只由小数位组成,则返回真,如下图所示。
myStr = "11"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))
输出。
11 consists of only digits:True
如果字符串包含除小数点以外的任何其他字符,isdigit() 方法将返回False 。你可以在下面的例子中观察到这一点。
myStr = "Aditya"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))
输出结果。
Aditya consists of only digits:False
我们可以使用isdigit() 方法来避免将字符串转换为整数时出现ValueError异常。为此,我们将首先对字符串调用isdigit() 方法。如果它返回True ,我们将使用int() 函数来将字符串转换为整数。否则,我们将说该字符串不能被转换为整数。你可以在下面的例子中观察到这一点。
myStr = "Aditya"
is_digit = myStr.isdigit()
if is_digit:
myInt=int(myStr)
print("The integer is:",myInt)
else:
print("'{}' cannot be converted into integer.".format(myStr))
输出。
'Aditya' cannot be converted into integer.
现在我们已经讨论了int() 函数和isdigit() method, let's 的工作,现在讨论在 python 中将字符串列表转换为整数的不同方法。
在Python中使用for Loop将字符串列表转换为整数
为了在Python中把字符串列表转换为整数,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储整数。 - 然后,我们将使用for循环来迭代字符串列表。
- 在迭代过程中,我们将首先使用
isdigit()方法检查当前字符串是否可以转换为int。 - 如果该字符串可以转换为int,我们将使用
int()函数将该字符串转换为int。否则,我们将说当前的字符串不能转换为整数。 - 将字符串转换为int后,我们将使用
append()方法将其追加到new_list。当在new_list上调用append()方法时,将新创建的整数作为其输入参数并将其添加到new_list。 - 最后,我们将移动到输入列表中的下一个字符串。
执行for循环后,我们将得到new_list 中的整数列表。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = []
for string in myList:
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
new_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(string))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
在Python中使用for循环将一个字符串列表转换为Ints列表
为了使用 for 循环、int() 函数和isdigit() 函数将字符串列表转换为 ints,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储输出的列表。 - 之后,我们将使用for循环遍历输入列表的内部列表。
- 在for循环中,我们将创建一个名为
temp_list的空列表来存储从内部列表中获得的ints列表。 - 然后,我们将使用另一个for循环来迭代每个内部列表的元素。
- 在迭代内层列表的元素时,我们将首先使用
isdigit()方法检查当前字符串是否可以转换为int。 - 如果字符串可以转换为int,我们将使用
int()函数将字符串转换为int。否则,我们将说当前的字符串不能转换为整数。然后,我们将转到当前内部列表中的下一个字符串。 - 在将当前内列表的所有字符串转换为整数后,我们还将使用
append()方法将其追加到temp_list。 - 迭代完每个内部循环后,我们将使用
append()方法将temp_list追加到new_list。然后,我们将移动到列表列表中的下一个内部列表。
在执行for循环后,我们将得到包含整数元素而不是字符串的列表,如下例所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = []
for element in inner_list:
is_digit = element.isdigit()
if is_digit:
myInt = int(element)
temp_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(element))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
在上面的例子中,字符串'Aditya'不能被转换为一个int。因此,它在输出中被省略了。
使用List Comprehension将字符串列表转换为整数
python 中的列表理解被用来从现有的容器对象中创建新的列表。你可以使用列表理解代替 for 循环,将一个字符串列表转换为一个整数列表,如下所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
这种方法在调用int() 函数之前,没有检查字符串是否可以转换为int。因此,如果我们发现列表中的一个元素不能被转换成整数,程序有可能会遇到ValueError 异常。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出。
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
new_list = [int(element) for element in myList]
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <listcomp>
new_list = [int(element) for element in myList]
ValueError: invalid literal for int() with base 10: 'Aditya'
在上面的例子中,字符串'Aditya'不能被转换为一个int。由于这个原因,程序遇到一个ValueError异常。
异常导致程序突然终止。它可能会导致数据或程序中的工作丢失。
为了处理异常,使程序不至于突然终止,你可以使用python try-except块,如下图所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
new_list = [int(element) for element in myList]
print("The list of ints is:")
print(new_list)
except ValueError:
print("Some values in the input list can't be converted to int.")
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list can't be converted to int.
使用map()函数将一个字符串列表转换为Ints
map() 函数是用来使用一个单一的python语句将一个函数应用于一个容器对象的所有元素。它将一个函数作为其第一个输入参数,将一个容器对象作为其第二个输入参数。执行后,它返回一个包含输出元素的map对象。
为了将字符串列表转换为ints,我们首先将int函数作为其第一个输入参数,将字符串列表作为其第二个参数,从而获得map对象。一旦我们得到map对象,我们将使用list() 构造函数将其转换为一个列表。这个列表将包含所有元素的整数。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = list(map(int,myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
同样,这种方法在调用int() 函数之前没有检查字符串是否可以转换为int。因此,如果我们发现列表中的一个元素不能被转换成整数,程序有可能会遇到ValueError 异常。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = list(map(int, myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出。
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
new_list = list(map(int, myList))
ValueError: invalid literal for int() with base 10: 'Aditya'
为了处理异常,使程序不会突然终止,你可以使用python try-except块,如下图所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
new_list = list(map(int, myList))
print("The list of ints is:")
print(new_list)
except ValueError:
print("Some values in the input list couldn't be converted to int.")
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list couldn't be converted to int.
使用map()函数将一个字符串列表转换为Ints列表
为了使用 python 中的map() 函数将字符串列表转换为 Ints,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储输出列表。 - 之后,我们将使用for循环来迭代列表中的列表。
- 在迭代过程中,我们将首先通过传递int函数作为其第一个输入参数,并将内部的字符串列表作为其第二个参数,来获得每个内部列表的map对象。
- 一旦我们得到map对象,我们将使用
list()构造函数将其转换为一个列表。 - 这个列表将包含整数形式的内部列表的元素。我们将使用
append()方法将这个列表追加到new_list。然后,我们将移动到下一个内列表。
在执行for循环后,我们将得到包含整数元素的内层列表的列表,如下代码所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = list(map(int, inner_list))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
同样,在这种情况下,程序可能会运行到ValueError 异常。所以,不要忘记在程序中使用try-except块,如下图所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
try:
temp_list = list(map(int, inner_list))
new_list.append(temp_list)
except ValueError:
print("Some values couldn't be converted to int.")
print("The list of lists of ints is:")
print(new_list)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
使用eval()函数将一个字符串列表转换为Ints
eval() 函数是用来解析和评估一个Python语句的。eval() 函数将一个字符串作为其输入参数,解析该字符串,评估其值,并返回输出。
例如,我们可以将字符串“2+2” 传递给 eval 函数,它将返回 4 作为输出。你可以在下面的例子中观察到这一点。
x = eval('2+2')
print(x)
输出。
4
同样,当我们将一个只包含小数点的字符串传递给eval() 函数时,它会返回一个整数,如下图所示。
x = eval('11')
print(x)
输出。
11
如果输入的字符串包含数字以外的字母字符,程序将遇到一个NameError 异常。你可以在下面的例子中观察到这一点。
x = eval('Aditya')
print(x)
输出。
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 1, in <module>
x = eval('Aditya')
File "<string>", line 1, in <module>
NameError: name 'Aditya' is not defined
这里,术语'Aditya'被评估为一个变量名。因此,eval() 函数试图获得与变量 'Aditya' 相关的对象的值。然而,该程序不包含任何名为'Aditya'的变量。因此,该程序遇到了NameError 异常。
为了使用eval() 函数将一个字符串列表转换为整数,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储整数。 - 之后,我们将使用for循环来迭代字符串列表。
- 在迭代过程中,我们将首先使用
isdigit()方法检查当前字符串是否可以转换为int。 - 如果该字符串可以转换为int,我们将使用
eval()函数将该字符串转换为int。否则,我们将说当前的字符串不能转换为整数。 - 将字符串转换为int后,我们将使用
append()方法将其追加到new_list。 - 最后,我们将移动到输入列表中的下一个字符串。
在执行for循环后,我们将得到new_list 中的ints列表。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
new_list = []
for string in myList:
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
new_list.append(myInt)
else:
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(new_list)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
使用eval()函数将一个字符串列表转换为Ints列表
为了使用eval() 函数将字符串列表转换为整数,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储输出的列表。 - 之后,我们将使用for循环遍历输入列表的内部列表。
- 在for循环中,我们将创建一个名为
temp_list的空列表来存储从内部列表中获得的int值。 - 然后,我们将使用另一个for循环来迭代当前内部列表的元素。
- 在迭代内层列表的元素时,我们将首先使用
isdigit()方法检查当前字符串是否可以转换为int。 - 如果字符串可以转换为int,我们将使用
eval()函数将字符串转换为int。否则,我们将说当前的字符串不能被转换为整数。最后,我们将转到当前内列表中的下一个字符串。 - 在将当前内列表的所有字符串转换为整数后,我们将使用
append()方法将它们追加到temp_list。 - 迭代完每个内部循环后,我们将使用
append()方法将temp_list追加到new_list。然后,我们将移动到列表中的下一个内部列表。
在执行for循环后,我们将得到包含整数元素而不是字符串的列表,如下例所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = []
for element in inner_list:
is_digit = element.isdigit()
if is_digit:
myInt = eval(element)
temp_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(element))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
在Python中把字符串列表原地转换成整数
在前面几节中讨论的所有方法都会创建一个新的输出列表。如果我们想把输入列表中的元素从字符串转换成 int,而不是创建一个新的输出列表,我们可以使用int() 方法或eval() 方法来实现。
使用int()函数将字符串列表原地转换为英数
要使用int() 函数将一个字符串列表原位转换为整数,我们将使用以下步骤。
- 首先,我们将使用
len()函数找出字符串列表的长度。len()函数将列表作为其输入参数,并返回列表的长度。我们将把这个长度存储在变量list_len。 - 获得列表的长度后,我们将使用
range()函数创建一个从0到list_len的数字序列。range()函数接收list_len作为输入参数,并返回序列。 - 获得序列后,我们将使用for循环遍历该序列。在迭代过程中,我们将使用其索引访问列表中的每个元素。
- 在获得元素后,我们将检查它是否可以被转换为一个整数。为此,我们将使用
isdigit()方法。 - 如果字符串可以转换为整数,我们将使用
int()函数将字符串转换为整数。否则,我们将说当前的字符串不能被转换为整数。最后,我们将转到当前内列表中的下一个字符串。 - 在将当前内列表中的所有字符串转换为整数后,我们将把它们重新分配到输入列表中的原始位置。
执行for循环后,输入列表中的所有元素将被转换为整数。你可以在下面的例子中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
string = myList[index]
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
myList[index] = myInt
else:
myList.remove(string)
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
在上面的例子中,字符串'Aditya'不能被转换为整数。因此,我们使用remove()方法删除了这个字符串。
使用eval()函数将字符串列表就地转换为整数
你可以不使用int() 函数,而是使用eval() 函数将字符串列表转换为整数,如下所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
string = myList[index]
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
myList[index] = myInt
else:
myList.remove(string)
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)
输出。
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
在Python中把字符串列表转换为整数。
使用int()函数将一个字符串列表转换为Ints的原位。
我们也可以使用 int() 函数将一个字符串列表转换为整数。为此,我们将使用以下步骤。
- 我们将使用for循环遍历列表的内部列表。
- 对于每个内部列表,我们将使用
len()函数找到内部列表的字符串的长度。我们将把这个长度存储在变量list_len。 - 在获得内部列表的长度后,我们将使用
range()函数创建一个从0到list_len的数字序列。range()函数将list_len作为输入参数并返回序列。 - 获得序列后,我们将使用for循环遍历该序列。在迭代过程中,我们将使用其索引访问内部列表的每个元素。
- 在获得元素后,我们将检查它是否可以被转换为一个整数。为此,我们将使用
isdigit()方法。 - 如果字符串可以转换为整数,我们将使用
int()函数将字符串转换为整数。否则,我们将说当前的字符串不能被转换为整数。最后,我们将转到当前内列表中的下一个字符串。 - 在将当前内列表中的所有字符串转换为整数后,我们将把它们重新分配到输入内列表中的原始位置。
执行完上述步骤后,原始列表中的元素将被转换为整数。你可以在下面的例子中观察到这一点。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
list_len = len(inner_list)
sequence = range(list_len)
for index in sequence:
string = inner_list[index]
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
inner_list[index] = myInt
else:
print("'{}' cannot be converted into int.".format(string))
inner_list.remove(string)
print("The list of lists of ints is:")
print(myList)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
使用eval()函数将字符串列表原位转换为整数
你也可以不使用int() 函数,而是使用eval() 函数将一个字符串列表转换为Ints inplace,如下所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
list_len = len(inner_list)
sequence = range(list_len)
for index in sequence:
string = inner_list[index]
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
inner_list[index] = myInt
else:
print("'{}' cannot be converted into int.".format(string))
inner_list.remove(string)
print("The list of lists of ints is:")
print(myList)
输出。
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
结论
在这篇文章中,我们讨论了在python中把字符串列表转换为ints的不同方法。如果你需要将字符串列表转换为ints,你可以采用使用map() 函数的方法。如果你需要将字符串列表就地转换为ints,你可以使用文章最后两节讨论的方法。