Python function returning values ​​from a list of fewer

My function should take a list of integers and a specific integer and return numbers in the list that are less than a certain integer. Any tips?

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
+4
source share
3 answers

Use a list comprehension with the "if" filter to extract these 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 variables more generic names, because this code will work for any sequence, regardless of the type of elements in the sequence (provided, of course, that the comparisons are valid for the corresponding type).

>>> 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 However, there is already a similar answer, I would prefer to declare a function instead of binding a lambda expression.

+4
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)

:

[4, 6, 1]

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

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

Source: https://habr.com/ru/post/1614087/


All Articles