Python one-line “for” expression

后端 未结 6 1072
独厮守ぢ
独厮守ぢ 2020-12-08 03:55

I\'m not sure if I need a lambda, or something else. But still, I need the following:

I have an array = [1,2,3,4,5]. I need to put this array, for insta

6条回答
  •  没有蜡笔的小新
    2020-12-08 04:44

    Using elements from the list 'A' create a new list 'B' with elements, which are less than 10

    Option 1:

    A = [1, 1, 2, 3, 5, 8, 13, 4, 21, 34, 9, 55, 89]
    
    B = []
    for i in range(len(A)):
        if A[i] < 10:
            B.append(A[i])
    print(B)
    

    Option 2:

    A = [1, 1, 2, 3, 5, 8, 13, 4, 21, 34, 9, 55, 89]
    
    B = [A[i] for i in range(len(A)) if A[i] < 10]
    print(B)
    

    Result: [1, 1, 2, 3, 5, 8, 4, 9]

提交回复
热议问题