将列表项从字符串转换为 int(Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23375606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting list items from string to int(Python)
提问by swami_108
I have a list:
我有一个清单:
Student_Grades = ['56', '49', '63']
and I want to convert each of the entries to integers so that I can calculate an average.
我想将每个条目转换为整数,以便我可以计算平均值。
Here's my code for converting:
这是我的转换代码:
for i in Student_Grades:
Student_Grades = [int(i)]
I keep getting the error
我不断收到错误
invalid literal for int() with base 10: '56,'
and I don't know what to do.
我不知道该怎么办。
Here is my full code on how I got Student_Grades Choose_File = str(input("Please enter the exact name of the file to be read in (including file extention) : "))
这是我如何获得 Student_Grades Choose_File = str(input("请输入要读取的文件的确切名称(包括文件扩展名):")) 的完整代码
with open(Choose_File, "r") as datafile:
counter = 1
x = 1
Student_Grades = []
Read = datafile.readlines()
info = Read[counter]
Split_info = info.split()
n = len(Split_info)
while x < n:
Student_Grades.append(Split_info[x])
x = x + 2
The textfile has the format 'MECN1234 56, MECN1357 49, MATH1111 63'
文本文件的格式为“MECN1234 56、MECN1357 49、MATH1111 63”
采纳答案by Quintec
You should do this:
你应该做这个:
for i in range(len(Student_Grades)):
Student_Grades[i] = int(Student_Grades[i])
回答by xbb
In [7]:
Student_Grades = ['56', '49', '63']
new_list = [int(i) for i in Student_Grades]
print(new_list)
[56, 49, 63]
回答by Jan Vlcinsky
Apply int
on each item in the list and return it as a list:
应用于int
列表中的每个项目并将其作为列表返回:
>>> StudentGrades = ['56', '49', '63']
>>> res = list(map(int, StudentGrades)) # this call works for Python 2.x as well as for 3.x
>>> print res
[56, 49, 63]
Note about map
differences in Python 2 and 3
注意map
Python 2 和 3 的差异
In Python 2.x map
returns directly the list, so you may use
在 Python 2.x 中map
直接返回列表,因此您可以使用
>>> res = map(int, StudentGrades)
but in Python 3.x map
returns an iterator, so to get real list, it must be wrapped into list
call:
但是在 Python 3.x 中map
返回一个迭代器,所以要获得真正的列表,它必须被包装成list
调用:
>>> res = list(map(int, StudentGrades))
The later way works well in both version of Python
后一种方式在两个版本的 Python 中都运行良好