Python equivalent of Ruby's .select

后端 未结 3 1735
执念已碎
执念已碎 2021-01-12 13:34

I have an list/array, lets call it x, and I want to create a new list/array, lets call this one z, out of elements from x that match a

相关标签:
3条回答
  • 2021-01-12 14:17

    Using a list comprehension is considered "Pythonic":

    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    z = [i for i in x if i < 5]
    print z
    

    Output

    [1, 2, 3, 4]
    
    0 讨论(0)
  • 2021-01-12 14:26

    Python has a built-in filter function:

    lst = [1, 2, 3, 4, 5, 6]
    filtered = filter(lambda x: x < 5, lst)
    

    But list comprehensions might flow better, especially when combining with map operations:

    mapped_and_filtered = [x*2 for x in lst if x < 5]
    # compare to:
    mapped_and_filtered = map(lambda y: y*2, filter(lambda x: x < 5, lst))
    
    0 讨论(0)
  • 2021-01-12 14:28

    One option is to use list comprehension:

    >>> [a for a in x if a < 5]
    [1, 2, 3, 4]
    
    0 讨论(0)
提交回复
热议问题