简体   繁体   中英

Print comparison as a number instead true or false in python

I'm putting a array inside a filter to create another array that stores all of the numbers that get through the filter but I don't know how.

Here is my code that creates the filter:

def check(list1):
    # traverse the list
    for x in list1:
        if 80 >= x <= 100 :
            return True

    return False

list1 = X2[indexes2]
print check(list1)

You can try like this.

» I have tried it in Python2 as I saw the tags are related to that. You can try the same with Python3 as well.

1st way

>>> def check(x):
...     return 80 <= x <= 100: # x >= 80 and x <= 100 
... 
>>> l = [34, 67, 80, 21, 102, 100, 456, 99]
>>> 
>>> l2 = filter(check, l)
>>> l2
[80, 100, 99]
>>> 

2nd way

>>> def check(lst):
...     lst2 = []
...     for x in lst:
...         if 80 <= x <= 100: # x >= 80 and x <= 100
...             lst2.append(x)
...     return lst2
... 
>>> l = [1, 54, 81, 65, 100, 99, 32, 80, 45, 95]
>>> l2 = check(l)
>>> l2
[81, 100, 99, 80, 95]

您可以使用列表推导通过过滤条件的给定列表来创建新列表:

print([x for x in X2[indexes2] if 80 <= x <= 100])

You can use python's builtin filter for this:

bool(len(list(filter(lambda x: x <= 80, i))))

beware that your initial comparison was doing x <= 80 and x <= 100 , obviously could be simplified to x <= 80

You can create another array within check() , and append values that pass the filter to it and return that list back.

Also, you have a logic error in your comparison statement; you're checking if x is less than 80 and less than 100. If you want to check whether x falls between 80 and 100, then do:

if 80 <= x <= 100 :

An efficient one-line implementation would be print(any(map(lambda x: x <= 80, X2[indexes2]))) . ( 80 <= x <= 100 is probably what you meant to use.)

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