我是编程和学习python的新手,参考书 Python Programming Fundamentals 。这是我要处理的问题之一:
1:请求用户输入数字列表。
2:然后输出0到100之间的数字。
以下是我的代码:
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output = output.append(float(e))
else:
output = output
print("The number between 0 and 100 are ", output)
错误是:
File "c:\Users\HKGGAIT001\Desktop\1.py", line 7, in <module>
output = output.append(float(e))
builtins.AttributeError: 'NoneType' object has no attribute 'append
答案 0 :(得分:1)
假设您在Python 2.x
。
使用input
会导致Python尝试评估用户输入,这会导致问题,因为您希望它们输入数字列表。 raw_input
只会向您提供用户输入的内容,而不会尝试解析它。
list.append
就位,这意味着函数调用的副作用只会在调用它的对象上执行追加,而不是返回一个新对象。
试试这个:
s = raw_input("Please enter a list of numbers: ")
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
print("The number between 0 and 100 are ", output)
答案 1 :(得分:1)
假设您正在使用Python3(因为.split()不太可能在Python2中成功)
这部分没问题
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = s.split() # Now lst is a list of strings.
output = [] # Here is the beginning of the accumulator pattern
你可以像这样编写循环
for e in lst:
if 0 < float(e) < 100 : # inbetween 0 and 100
output.append(float(e))
请注意,有两个比较。隐含and
。这称为chained comparison
output = [float(e) for e in lst if 0 < float(e) < 100]
但现在我们需要使用float(e)
两次
我们可以使用其他list comprehension将lst
列为float
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = [float(e) for e in s.split()] # Now lst is a list of floats.
output = [e for e in lst if 0 < e < 100]
由于我们只需要迭代lst
一次,因此微小的变化会使其成为generator expression。所以你的最终计划可能是
s = input("Please enter a list of numbers:") # request user to input a list of numbers
lst = (float(e) for e in s.split()) # Now lst is a generator of floats.
output = [e for e in lst if 0 < e < 100]
print("The number between 0 and 100 are ", output)
答案 2 :(得分:1)
s = str(input("Please enter a list of numbers:"))
lst = s.split()
output = []
for e in lst:
if float(e) > 0 and float(e) < 100 :
output.append(float(e))
print("The number between 0 and 100 are ", output)
else:
print("The number less than 0 or greter than 100 ", e)
答案 3 :(得分:0)
s = input("Please enter a list of numbers:")
output = [each for each in s if each > 0.0 and each < 100.0]
print("The number between 0 and 100 are ", output)