我目前的代码如下:
num = input()
numlist = num.split(",")
def even(list):
string = ""
for number in list :
number = float(number)
if number %2 == 0:
string += "~"+str(number)
return(string)
def odd(list):
string = ""
for number in list:
number = float(number)
if number %2 != 0:
string += "~"+str(number)
return(string)
print "even numbers :" ,even(numlist)
print "odd numbers :" ,odd(numlist)
我的输出: 偶数:~56.0 奇数:~3.0~1.0~5.9~12.6~8.9
预期产量: 偶数:~56 奇数:~3~1~5.9~12.6~8.9 谢谢你的帮助
答案 0 :(得分:0)
因为你获得了字符串,所以在你的方法中使用split '.'
,即:
if string.split('.')[-1] == '0':
string = string.split('.')[0]
完整计划:
num = input()
numlist = num.split(",")
def even(list):
string = ""
for number in list :
number = float(number)
if number %2 == 0:
string += "~"+str(number)
if string.split('.')[-1] == '0':
string = string.split('.')[0]
return(string)
def odd(list):
string = ""
for number in list:
number = float(number)
if number %2 != 0:
string += "~"+str(number)
if string.split('.')[-1] == '0':
string = string.split('.')[0]
return(string)
print ("even numbers :" ,even(numlist))
print ("odd numbers :" ,odd(numlist))
示例输出:
5,5.6
even numbers :
odd numbers : ~5~5.6
注意:不应在浮点数上使用模数。这里它只考虑整数部分而不是小数。
答案 1 :(得分:0)
执行此操作的简单方法是将原始字符串从numlist
附加到输出字符串。
我还更改了函数参数的名称:不应将list
用作变量名,因为它会影响内置list
类型。
def even(lst):
string = ""
for s in lst :
number = float(s)
if number %2 == 0:
string += "~" + s
return string
def odd(lst):
string = ""
for s in lst:
number = float(s)
if number %2 != 0:
string += "~" + s
return string
# Test
data = '3,1,56,5.9,12.6,8.9'
numlist = data.split(',')
print numlist
print "even numbers :" ,even(numlist)
print "odd numbers :" ,odd(numlist)
<强>输出强>
['3', '1', '56', '5.9', '12.6', '8.9']
even numbers : ~56
odd numbers : ~3~1~5.9~12.6~8.9
答案 2 :(得分:0)
您可以使用浮点数的is_integer()方法检查浮点数是否为整数。如果它是一个整数,你将它转换为int,否则你就像它一样。 所以你可以这样做:
num = input()
numlist = num.split(",")
def even(list):
string = ""
for number in list :
number = float(number)
if number.is_integer():
number = int(number)
if number %2 == 0:
string += "~"+str(number)
return(string)
def odd(list):
string = ""
for number in list:
number = float(number)
if number.is_integer():
number = int(number)
if number %2 != 0:
string += "~"+str(number)
return(string)
print "even numbers :" ,even(numlist)
print "odd numbers :" ,odd(numlist)
输入:56,3,5.9,12.6,8.9
输出:偶数:~56
奇数:~3~5.9~12.6~8.9
无论如何,我同意其他人的说法,将模数与非整数一起使用真的很奇怪。