Python 如何将字符串列表更改为整数列表
我正在编写一个程序,它获取一个用户文件(在本例中是一个数字列表),并计算列表的平均值、中位数和模式。然而,我在弄清楚如何将数字字符串转换成整数时遇到了很多困难。当我尝试的时候,我得到了一个错误:“以10为基数的int()的无效文本”,然后是我列表的第一个数字。无论我尝试什么,我似乎无法转换列表,即使这是我一直看到的解决方案。因此,当我对列表排序时,它不会按数字顺序排序。我的模式功能似乎也不太好用,甚至几天后我也不明白为什么。我想附上文件,但似乎没有办法,对不起。希望这是足够的信息来了解可能导致问题的原因Python 如何将字符串列表更改为整数列表,python,scripting,Python,Scripting,我正在编写一个程序,它获取一个用户文件(在本例中是一个数字列表),并计算列表的平均值、中位数和模式。然而,我在弄清楚如何将数字字符串转换成整数时遇到了很多困难。当我尝试的时候,我得到了一个错误:“以10为基数的int()的无效文本”,然后是我列表的第一个数字。无论我尝试什么,我似乎无法转换列表,即使这是我一直看到的解决方案。因此,当我对列表排序时,它不会按数字顺序排序。我的模式功能似乎也不太好用,甚至几天后我也不明白为什么。我想附上文件,但似乎没有办法,对不起。希望这是足够的信息来了解可能导致问
def CalculateMode(numbers):
dictionary = dict()
for num in numbers:
if num in dictionary:
dictionary[num] = dictionary[num] + 1
else:
dictionary[num] = 1
maximum = max(dictionary.values())
for key in dictionary:
if dictionary[key] == maximum:
print("The mode is " + key + ".")
def Main():
openFile = open("testfile.txt", 'r')
data = openFile.read()
numbers = data.split()
for num in numbers:
num = int(num)
return num
numbers = sorted(numbers)
print(numbers)
while True:
choice = input("Calculate Mode [1] Exit [2]: ")
if choice == "1":
CalculateMode(numbers)
elif choice == "2":
break
else:
print("Please choose one of the above options.")
Main()
尝试使用int(float(所需的字符串))
您试图转换的字符串不能转换为int
编辑:正如gold_cy所说,代码中存在逻辑上的不一致,超出了所显示的错误范围。一个选项是尽可能多地使用代码 注意:根据Python约定将变量重命名为: 函数名应该是小写的,单词之间用 必要时加下划线以提高可读性 变量名遵循与函数名相同的约定 代码
import re
def calculate_mode(numbers):
dictionary = dict()
for num in numbers:
if num in dictionary:
dictionary[num] = dictionary[num] + 1
else:
dictionary[num] = 1
maximum = max(dictionary.values())
for key in dictionary:
if dictionary[key] == maximum:
print(f"The mode is {key}.")
def main():
with open("testfile.txt", 'r') as open_file:
# Extract consecutive digits using regex
# (see https://www.geeksforgeeks.org/python-extract-numbers-from-string/)
data = re.findall(r"\d+", open_file.read())
# Convert digits to integer
numbers = [int(x) for x in data]
# Sort numbers (inplace)
numbers.sort()
print(numbers)
while True:
choice = input("Calculate Mode [1] Exit [2]: ")
if choice == "1":
calculate_mode(numbers)
elif choice == "2":
break
else:
print("Please choose one of the above options.")
main()
输入文件(testfile.txt)
输出
2, 3, 4, 5,
7, 9, 3, 2
1, 2, 9, 5
4, 2, 1, 8
6, 3, 4, 5
[1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 7, 8, 9, 9]
Calculate Mode [1] Exit [2]: 1
The mode is 2.
Calculate Mode [1] Exit [2]:
您的代码在尝试转换为整数后返回,这就是为什么下面的代码不会运行。此外,文本文件的结构如何文本文件的结构是一个数字列表,如下所示:1、2、3、4、5它们之间用逗号和空格分隔。拆分时,在每个数字后留下一个逗号,这就是为什么拆分失败的原因。您需要执行
split(',')
在命令上进行拆分如果数据是一个字符串,如“1,2,3,4,5”,那么data.split()将生成[“1,”,“2,”,“3,”,“4,”,“5,”]。如果您在“,”上拆分,即data.split(','),这将生成整数[1,2,3,4,5]。但是,如果使用“\n”,您仍然会遇到问题。你能发布几行数据以便我们提供更好的反馈吗?文件中能有新行吗?还是只有一条线?数字只能是整数,还是也可以是浮点数?