[英]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.