2024-05-29 01:32:40 发布
网友
我在Python中有一个方法,我只想接受列出的整数或单数,我如何定义它?你知道吗
def autoInt(integers): assert int(integers) assert len(integers) > 0
这失败了,因为我没有一个列表。我相信这很简单。你知道吗
TypeError: int() argument must be a string or a number, not 'list'
编辑:我已经被指派了任务,所以这个方法只能接受列表中的整数。你知道吗
>>> my_list = [1, 2, 3.25] >>> all(isinstance(item, int) for item in my_list) False >>> other_list = range(3) >>> all(isinstance(item, int) for item in other_list) True >>>
来源:https://stackoverflow.com/a/6009630/6748523
您可以像这样测试整数列表:
assert(all(isinstance(item, int) for item in integers))
从How to test if every item in a list of type 'int'?
这取决于根据你的定义什么是整数。例如,bool的实例计数吗?浮动1.0吗?你知道吗
bool
1.0
无论如何-您可以将all内置函数与生成器表达式结合起来。你知道吗
all
>>> a = [1,2,True] >>> all(isinstance(x, int) for x in a) True >>> all(type(x) == int for x in a) False
作为旁注:严格检查参数类型并不是Python程序员在没有特定原因时所做的事情。更好的方法通常是编写清晰的docstring和/或类型提示。你知道吗
Here是一个解释如何做后者的答案。除此之外,通常还有一种“垃圾输入-垃圾(或错误)”的心理。你知道吗
来源:https://stackoverflow.com/a/6009630/6748523
您可以像这样测试整数列表:
从How to test if every item in a list of type 'int'?
这取决于根据你的定义什么是整数。例如,
bool
的实例计数吗?浮动1.0
吗?你知道吗无论如何-您可以将
all
内置函数与生成器表达式结合起来。你知道吗作为旁注:严格检查参数类型并不是Python程序员在没有特定原因时所做的事情。更好的方法通常是编写清晰的docstring和/或类型提示。你知道吗
Here是一个解释如何做后者的答案。除此之外,通常还有一种“垃圾输入-垃圾(或错误)”的心理。你知道吗
相关问题 更多 >
编程相关推荐