Python one-line “for” expression

2019-02-03 06:45发布

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 instance, into another array. But write it all in one line.

for item in array:
    array2.append(item)

I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.

Update: let's say this: array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE

(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with)

标签: python lambda
6条回答
戒情不戒烟
2楼-- · 2019-02-03 06:56

If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:

a1 = [1,2,3,4,5]
a2 = [6,7,8,9]
a1 + a2
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]
查看更多
在下西门庆
3楼-- · 2019-02-03 07:00
for item in array: array2.append (item)

Or, in this case:

array2 += array
查看更多
beautiful°
4楼-- · 2019-02-03 07:00

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]

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-03 07:05

Even array2.extend(array1) will work.

查看更多
冷血范
6楼-- · 2019-02-03 07:11

If you're trying to copy the array:

array2 = array[:]
查看更多
我命由我不由天
7楼-- · 2019-02-03 07:19

The keyword you're looking for is list comprehensions:

>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
查看更多
登录 后发表回答