如何将字符串列表更改为整数列表

问题描述 投票:0回答:2

我正在编写一个程序,该程序接收用户文件(在这种情况下为数字列表),并计算列表的均值,中位数和众数。但是,我在弄清楚如何将数字字符串转换为整数方面遇到很多麻烦。当我尝试时,出现错误:“ int()在基数10中无效的文字”,然后是列表的第一个数字。无论我尝试什么,即使这是我一直看到的解决方案,我似乎也无法转换列表。因此,当我对列表进行排序时,它不会按数字顺序进行排序。我的模式功能似乎也无法很好地工作,即使过了几天,我也不知道为什么。我会附加文件,但是似乎没有办法做到这一点,对不起。希望这是足够的信息,以查看可能导致问题的原因。

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()
python scripting
2个回答
1
投票

以下是一个使用尽可能多的代码的选项。

注意:将变量重命名为遵循Python约定Pep 8,即:

函数名称应为小写,单词之间用强调必要以提高可读性。

变量名与函数名遵循相同的约定。

代码

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]:

0
投票

尝试使用int(float(desired_string))进行投射

您尝试转换的字符串不能转换为int。

编辑:正如gold_cy所说,您的代码中存在逻辑上的不一致,这超出了所显示的错误。

© www.soinside.com 2019 - 2024. All rights reserved.