简体   繁体   English

如何在 python 中进行切片和使用 any()?

[英]How to do slicing and use any() in python?

I am trying to find the numbers smaller than the number(here i) towards the right of a list我试图找到小于列表右侧的数字(此处为 i)的数字

If here 1,2,3,4 for any number there is no number towards its right which is smaller than that.I want to implement with any() and slicing.如果这里 1,2,3,4 表示任何数字,则右侧没有小于该数字的数字。我想用 any() 和切片来实现。

But when I did that in python with the following code I am getting True but it should be False where am I missing the logic?但是当我在 python 中使用以下代码执行此操作时,我得到了 True 但它应该是 False 我在哪里遗漏了逻辑? and why is the output as True?为什么 output 为 True?

num=[1,2,3,4]

for i in range(1,len(num)-1):
    print (any(num[i+1:])<num[i])

Output: Output:

True
True

The any function should take a sequence of booleans, usually given by a generator expression. any function 都应该采用一系列布尔值,通常由生成器表达式给出。 The reason your code outputs True is because num[i+1:] is a list of non-zero ints, which are considered "truthy", so the answer to "are any of them true?"您的代码输出True的原因是因为num[i+1:]是一个非零整数列表,它们被认为是“真实的”,所以“它们中的任何一个都是真的吗?”的答案is "yes".是是的”。

You can write something like this:你可以这样写:

num = [1,2,3,4]

for i in range(1, len(num) - 1):
    print(any( x < num[i] for x in num[i+1:] ))

Output: Output:

False
False

You need to check what's actually happening here.您需要检查这里实际发生的情况。 You have:你有:

any(num[i+1:]) < num[i]

any returns true if any of the elements of the list equivalent to true.如果列表中的任何元素等效于 true,则any返回 true。 Since all your numbers are non-zero, they are all equivalent to true.因为你所有的数字都是非零的,它们都等价于真。 Then the right side compares to True to num[i] , so you have True < 2 and True < 3 .然后右侧将Truenum[i]进行比较,因此您有True < 2True < 3 Since True is equivalent to 1 these both result in 1.因为True等价于1 ,所以这两个结果都是 1。

You probably want something like:你可能想要这样的东西:

print( any(x < num[i] for x in num[i+1:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM