【问题标题】:Keep getting not all arguments converted during string formatting in python在 python 中的字符串格式化期间,不是所有的参数都被转换
【发布时间】:2019-02-25 13:07:28
【问题描述】:

我在第 6 行中不断收到错误消息,我不知道为什么。它一直说在字符串格式化期间并非所有值都被转换。我正在尝试创建一个程序来识别一串数字中的唯一数字。

   def iq_test(numbers):
        oddlist = []
        evenlist = []
        numbers = numbers.split()
        for x in numbers:
            if x % 2 == 0:
                evenlist.append(x)
            if x % 2 != 0:
                oddlist.append(x)
        if len(evenlist) > len(oddlist):
            return "".join(oddlist)
        else:
            return "".join(evenlist)

【问题讨论】:

  • 你传递给这个函数的是什么?
  • 您已拆分数字字符串。拆分后的字符串编号是一种字符串。所以拆分后将字符串转换为int。 int(x) 在循环中的 x 位置也是如此
  • 所以它会是:for int(x) in numbers?

标签: python arrays python-3.x string list


【解决方案1】:

看起来这个函数应该从输入列表中返回较短的偶数或奇数列表。在你的.split() 之后,结果是一个字符串列表,所以数学基本上是这样的:

>>> "1" % 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

解决方法如下:

def iq_test(numbers):
        oddlist = []
        evenlist = []

        # Splitting the input strings returns a list of strings.
        # Use a list comprehension to convert them to integers.
        numbers = [int(x) for x in numbers.split()]

        for x in numbers:
            if x % 2 == 0:
                evenlist.append(x)
            else: # Can just use an else here
                oddlist.append(x)
        if len(evenlist) > len(oddlist):
            return oddlist # No need for the join now
        else:
            return evenlist # No need for join.

data = input('Numbers? ')
result = iq_test(data)
print(result)

输出:

Numbers? 1 2 3 4 5
[2, 4]

【讨论】:

  • 非常感谢。这行得通,我已经意识到我的错误!
【解决方案2】:

Python 的split 函数返回一个字符串列表。因此,for 循环中的每个 x 值实际上是任何数字 x 的字符串表示形式。这意味着您对x 执行的任何算术/数值运算都将失败,因为您无法对字符串执行数值运算。

只需执行int(x) 即可将任何数字字符串转换为int。 (即int("3") % 2 == 1

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 2013-03-07
    • 2022-06-12
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2013-10-21
    相关资源
    最近更新 更多