为什么我的 Python 代码返回类型错误?
Why is my Python code returning a TypeError?
我想要一个函数来检查字符串中的数字是否为奇数。我希望它打印出奇数的位置,但第 4 行给出 'TypeError: not all arguments converted during string formatting'。我该如何解决?
代码如下:
def IQ_test(string):
numbers = string.split()
for x in numbers:
if x % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
使用int()
将chars转换为int类型:
def IQ_test(string):
numbers = string.split()
for x in numbers:
if int(x) % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
使用它:
def IQ_test(string):
numbers = string.split(' ')
for x in numbers:
if int(x) % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
正如其他人已经在该线程中提到的,您没有将 numbers
列表中的元素转换为 int
类型。
但我想强调一下您的逻辑中可能存在的错误:
使用 numbers.index(x)
您将在列表中找到元素 x
的第一次出现,因此如果相同的数字重复多次,您将始终获得第一个索引。
如果这不是您想要的行为,您可以这样做:
for index, x in enumerate(numbers):
if int(x) % 2 != 0:
print(index)
我想要一个函数来检查字符串中的数字是否为奇数。我希望它打印出奇数的位置,但第 4 行给出 'TypeError: not all arguments converted during string formatting'。我该如何解决? 代码如下:
def IQ_test(string):
numbers = string.split()
for x in numbers:
if x % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
使用int()
将chars转换为int类型:
def IQ_test(string):
numbers = string.split()
for x in numbers:
if int(x) % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
使用它:
def IQ_test(string):
numbers = string.split(' ')
for x in numbers:
if int(x) % 2 != 0:
print(numbers.index(x))
IQ_test("1 4 7 5 2")
正如其他人已经在该线程中提到的,您没有将 numbers
列表中的元素转换为 int
类型。
但我想强调一下您的逻辑中可能存在的错误:
使用 numbers.index(x)
您将在列表中找到元素 x
的第一次出现,因此如果相同的数字重复多次,您将始终获得第一个索引。
如果这不是您想要的行为,您可以这样做:
for index, x in enumerate(numbers):
if int(x) % 2 != 0:
print(index)