简体   繁体   English

将列表中的字符串转换为 int - 不转换

[英]Conversion of strings in list to int - not converting

I am trying to convert a list which previously has some integer values, strings and floats all to integers, however am running into some issues during the conversion.我正在尝试将以前具有一些整数值、字符串和浮点数的列表转换为整数,但是在转换过程中遇到了一些问题。 Here is what I have done:这是我所做的:

class NumbersIterable:
    def __init__(self, numbers):
        self.numbers = numbers
        print(self.numbers)
    
    def runConversion(self):
        return NumbersIterator.convertNumbers(self.numbers)

class NumbersIterator:
    def convertNumbers(numbers):
        print('in numbers')
        for i in numbers:
            int(i)
        print(numbers)
        return numbers

niterable = NumbersIterable(["1", 2.0, "4",5,6.1,"7",8,9.2])
niterable = niterable.runConversion()

sum = 0
for i in niterable:
    print(i)
    sum += i
print("sum =", sum)

I have some print statements along the way to verify the process, however after it runs through the for loop in NumbersIterator, the print statement shows the values in the list are not converted to integers and as such a error is thrown when running the for loop further down.我一路上有一些打印语句来验证该过程,但是在它通过 NumbersIterator 中的 for 循环后,打印语句显示列表中的值未转换为整数,因此在运行 for 循环时会引发错误再向下。

Is there anything I might be missing/spelling incorrectly here?有什么我可能遗漏/拼写错误的地方吗? Thanks谢谢

You can use a simple list comprehension to convert all numbers:您可以使用简单的列表理解来转换所有数字:

def convertNumbers(numbers):
    return [int(i) for i in numbers]

In your code, int(i) converts i into an integer, and then throws it away.在您的代码中, int(i)i转换为整数,然后将其丢弃。 You need to store the converted value in a list.您需要将转换后的值存储在列表中。 One way of doing so, among many others, is initializing an empty list and then appending int(i) :这样做的一种方法是初始化一个空列表,然后附加int(i)

class NumbersIterator:
    def convertNumbers(numbers):
        print('in numbers')
        output = []
        for i in numbers:
            output.append(int(i))
        print(numbers)
        return output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM