简体   繁体   中英

Python function that returns values from list smaller than a number

My function needs to take in a list of integers and a certain integer and return the numbers in the list that are smaller than the specific integer. Any advice?

def smallerThanN(intList,intN):
    y=0
    newlist=[]
    list1=intList
    for x in intList:
        if int(x)  < int(intN):
            print(intN)
            y+=1
            newlist.append(x)
    return newlist

Use a list comprehension with an "if" filter to extract those values in the list less than the specified value:

def smaller_than(sequence, value):
    return [item for item in sequence if item < value]

I recommend giving the variables more generic names because this code will work for any sequence regardless of the type of sequence's items (provided of course that comparisons are valid for the type in question).

>>> smaller_than([1,2,3,4,5,6,7,8], 5)
[1, 2, 3, 4]
>>> smaller_than('abcdefg', 'd')
['a', 'b', 'c']
>>> smaller_than(set([1.34, 33.12, 1.0, 11.72, 10]), 10)
[1.0, 1.34]

NB There is already a similar answer, however, I'd prefer to declare a function instead of binding a lambda expression.

integers_list = [4, 6, 1, 99, 45, 76, 12]

smallerThan = lambda x,y: [i for i in x if i<y]

print smallerThan(integers_list, 12)

Output:

[4, 6, 1]

def smallerThanN(intList, intN):
    return [x for x in intList if x < intN]

>>> smallerThanN([1, 4, 10, 2, 7], 5)
[1, 4, 2]

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