我是Python的初学者,我尝试从stdin获取数字列表,然后将最接近的数字显示为0.
这是我到目前为止所做的。
import sys
list = sys.stdin.readline().split()
print(min(list, abs))
但是我用这段代码得到的输出是
<built-in function abs>
你能帮我吗?
答案 0 :(得分:2)
python 2.x:
lis = raw_input("enter str").split()
python 3.x:
lis = input("enter str").split()
并将print(min(list, abs))
修复为:
print (abs(int(min(lis, key = lambda x: abs(int(x))))))
最短的是:
print (abs(int(min(input("enter str").split(), key = lambda x: abs(int(x))))))
答案 1 :(得分:1)
min
的Full traceback:
Traceback (most recent call last):
File "pymask.py", line 303, in <module>
main(sys.argv)
File "pymask.py", line 285, in main
keras.callbacks.ProgbarLogger()
File "/home/danielunderwood/virtualenvs/keras/lib/python3.6/site-packages/keras/engine/training.py", line 1557, in fit_generator
class_weight=class_weight)
File "/home/danielunderwood/virtualenvs/keras/lib/python3.6/site-packages/keras/engine/training.py", line 1314, in train_on_batch
check_batch_axis=True)
File "/home/danielunderwood/virtualenvs/keras/lib/python3.6/site-packages/keras/engine/training.py", line 1029, in _standardize_user_data
exception_prefix='model input')
File "/home/danielunderwood/virtualenvs/keras/lib/python3.6/site-packages/keras/engine/training.py", line 52, in standardize_input_data
str(names))
ValueError: No data provided for "input_1". Need data for each key in: ['input_1']
- 参数仅限关键字,因此您需要像这样传递它:
key
否则它会尝试检查min(lst, key=abs)
是否将列表与功能进行比较,从而导致&#34; 意外&#34;结果(功能较小!)。
但是你需要将项目转换为整数(或float s?)(否则lst < abs
将应用于字符串),例如使用map
:
abs
您提到您只对最小的正数感兴趣,在这种情况下您可以使用:
lst = map(int, sys.stdin.readline().split()) # or float instead of "int" if you expect decimals
或全部在一行:
lst = map(int, sys.stdin.readline().split()) # identical
positives = filter(lambda x: x >= 0, lst) # remove numbers below 0
min(positives)