简体   繁体   中英

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

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.

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? and why is the output as True?

num=[1,2,3,4]

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

Output:

True
True

The any function should take a sequence of booleans, usually given by a generator expression. 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?"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:

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. 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 . Since True is equivalent to 1 these both result in 1.

You probably want something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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