为什么排序列表检测在这种情况下不起作用?
我的目标是让python代码允许检测列表是否已排序。
My goal is to have python code allowing to detect if a list is sorted or not.
我想了解为什么以下代码返回 True
而不是我的预期猜测 False
I would like to understand why the following code return True
instead of my expected guess False
l = [1, 2, 3, 4, 1, 6, 7, 8, 7]
all(l[i] <= l[i+1] for i in xrange(len(l)-1)) # return "True"
注意:
- 我在 iPython 0.10中使用python 2.6.4
- 我使用非常大的列表所以我我宁愿避免
类型的解决方案l == l.sort()
- I'm using python 2.6.4 inside iPython 0.10
- I use very huge list so I'd prefer to avoid
solution of type
l == l.sort()
在理解这一点的方式中,我已经从以下两篇主要内容中读取(和测试)信息:
In the way to understand this I already read (and test) info from the main two following post:
- https://stackoverflow.com/a/3755251/4716013
- https://stackoverflow.com/a/4710776/4716013
- https://stackoverflow.com/a/3755251/4716013
- https://stackoverflow.com/a/4710776/4716013
显然问题显然只出现在iPython内部,而不是只使用python命令行!
OK apparently the problem appear inside iPython ONLY, not when using only python command line!
iPython 0.10
In [93]: l = [1, 2, 3, 4, 1, 6, 7, 8, 7]
In [94]: all(l[i] <= l[i+1] for i in xrange(len(l)-1))
Out[94]: True
python 2.6.4
>>> l = [1, 2, 3, 4, 1, 6, 7, 8, 7]
>>> all(l[i] <= l[i+1] for i in xrange(len(l)-1))
False
我能够在我的机器上重现类似的问题。然而,在挖掘之后,发生了所有
函数不是内置函数,而是来自numpy( all .__ module__ =='numpy。 core.fromnumeric'
)。
I was able to reproduce a similar problem on my machine. However, after digging, it occurred that the all
function was not the built-in function but came from numpy (all.__module__ == 'numpy.core.fromnumeric'
).
问题是你要创建一个生成器而不是列表。例如:
The problem is that you are creating a generator rather than a list. For example:
all(x>5 for x in xrange(3))
# <generator object <genexpr> at 0x1153bf7d0>
all([x>5 for x in xrange(3)])
# False
if all(x>5 for x in xrange(3)):
print True
else:
print False
# prints True
if all([x>5 for x in xrange(3)]):
print True
else:
print False
# prints False
只需在表达式中添加 [...]
:
all([l[i] <= l[i+1] for i in xrange(len(l)-1)])
# False
如果你需要创建一个列表,那么更有效的解决方案就是做一个简单的for循环:
If it is the case that you need to create a list, a more efficient solution would be to do a simple for loop:
for i in xrange(len(l)-1):
if l[i] > l[i+1]:
result = False
break
else:
result = True
如果像我一样,你覆盖了内置的所有
功能,你可以做 del all
来恢复它。之后,你应该有 all .__ module__ =='__ builtin __'
。如果仍然不是这样,只需要 all = __builtin __。所有
If like me, you overrode the built-in all
function, you can do del all
to recover it. After that, you should have all.__module__ == '__builtin__'
. If that's still not the case, just do all = __builtin__.all