为什么会发生此错误,我该如何解决?
我正在尝试将此代码编写为代码战中的一种实践。
def iq_test(numbers):
splitted_num=numbers.split()
list_numbers= list(splitted_num)#splitted string was already a list
odds = [x for x in list_numbers if x%2!=0]
evens= [x for x in list_numbers if x%2==0]
return (odds.index[0, 1] if len(odds)<len(evens) else evens[0, 1])
numbers= ("2 4 7 8 10")
print(iq_test(numbers))
错误:
Traceback (most recent call last):
File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 13, in <module>
print(iq_test(numbers))
File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in iq_test
odds = [x for x in list_numbers if x%2!=0]
File "C:\Users\Masoud\Desktop\Python Exercises\codewars\9_IQ Test.py", line 8, in <listcomp>
odds = [x for x in list_numbers if x%2!=0]
TypeError: not all arguments converted during string formatting
这是问题:
鲍勃正在准备通过智商测试。此测试中最常见的任务是找出给定数字中的哪个不同于其他数字。鲍勃(Bob)发现,一个数字通常在均匀性上与其他数字不同。帮助Bob-检查他的答案,他需要一个程序,该程序在给定的数字中找到一个均匀度不同的数字,然后返回该数字的位置。题: !请记住,您的任务是帮助Bob解决真正的IQ测试,这意味着元素的索引从1(而不是0)开始
最佳答案
如果这是你的目标
鲍勃正在准备通过智商测试。此测试中最常见的任务是找出给定数字中的哪个不同于其他数字。鲍勃(Bob)发现,一个数字通常在均匀性上与其他数字不同。帮助Bob-检查他的答案,他需要一个程序,该程序在给定的数字中找到一个均匀度不同的数字,然后返回该数字的位置。题: !请记住,您的任务是帮助Bob解决真正的IQ测试,这意味着元素的索引从1(而不是0)开始
这应该做
def iq_test(numbers):
splitted_num=numbers.split()
# to make all the strings to characters
list_numbers = list(map(int,splitted_num))
odds = [x for x in list_numbers if x%2!=0]
evens= [x for x in list_numbers if x%2==0]
# you're trying to return the index of the different number among the given list
# + 1 is that for index starts at 0 so the position will be index + 1
return list_numbers.index(odds[0])+1 if len(odds) == 1 else list_numbers.index(evens[0])+1
numbers = ("2 4 7 8 10")
print(iq_test(numbers))
关于python - : TypeError: not all arguments converted during string formatting的原因和建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62105251/