简体   繁体   English

尝试运行 python 代码时出现 TypeError

[英]Getting TypeError when try to run the python code

Following code is used to get the input from the user and then print out the odd numbers in the user input以下代码用于获取用户的输入,然后打印出用户输入中的奇数

list2 = [ list2 for list2 in input("list").split(",")]

odd_nos = [ num for num in list2 if num % 2 !=0]

print ("Odd numbers in the list: ",odd_nos)

BUT, I run into the following error when trying to run above piece of code但是,当我尝试运行上面的代码时遇到以下错误

odd_nos =[ num for num in list2 if num % 2 !=0]

TypeError: not all arguments converted during string formatting

Appreciate if you can help me on this.感谢您能在这方面帮助我。

Simple fix--needed int(num), since num is a string.简单的修复——需要 int(num),因为 num 是一个字符串。

list2 = [ list2 for list2 in input("list").split(",")]
odd_nos = [ int(num) for num in list2 if int(num) % 2 !=0]
print ("Odd numbers in the list: ",odd_nos)

Or one-liner或者单线

odd_nos = [int(x) for x in input('Enter list').split(',') if int(x) % 2]

Here is the solution:这是解决方案:

list2 = [int(list2) for list2 in lst.split(",")]
odd_nos = [ num for num in list2 if num % 2 !=0]
print ("Odd numbers in the list: ",odd_nos)

暂无
暂无

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

相关问题 当我尝试运行我的代码时,我不断收到 TypeError: 'str' object 不能解释为 integer - I keep getting TypeError: 'str' object cannot be interpreted as an integer when i try to run my code 当我尝试运行这段代码时,我不断收到命名错误(Python) - I keep getting a naming error when i try to run this piece of code (Python) 当我尝试使用 droidcam 运行我的 CV2 python 代码时出现错误 - When I try to run my CV2 python code with droidcam I am getting error 为什么当我尝试运行此 tkinter python 代码时会出现问题 - Why is there a problem when i try to run this tkinter python code 超出时间限制错误 - 当我尝试运行 Python 3 代码时 - Time limit exceeded Error - When I try to run Python 3 code 为什么每次尝试运行 VS Code python 终端时都会出现语法错误? - Why am I getting a syntax error whenever I try to run VS code python terminal? 在 python 3 中使用 Blank 或 Null 键执行代码时出现“TypeError”,而相同的代码适用于 python2 - Getting “TypeError” when executing code with Blank or Null key in python 3 whereas same code works fine with python2 我尝试运行此代码时遇到错误-/不支持的操作数类型:“ str”和“ int” - I'm getting an error when I try to run this code - unsupported operand type(s) for /: 'str' and 'int' Python 当我尝试将 VSCode 中的项目作为代码运行时,它们以“code=1”退出 - Python Projects In VSCode Exit With "code=1" When I Try to Run Them as Code 当我尝试在终端上运行代码时,我不断收到“ModuleNotFound”错误,即使我安装了它 - I keep getting "ModuleNotFound" error when i try to run code on my terminal even though i installed it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM