简体   繁体   English

Python单行“for”表达式

[英]Python one-line “for” expression

I'm not sure if I need a lambda, or something else. 我不确定我是否需要lambda或其他东西。 But still, I need the following: 但是,我仍然需要以下内容:

I have an array = [1,2,3,4,5] . 我有一个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 更新:让我们这样说: 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) (这个例子不是真的。我只是想迭代不同的数据块,但这是我能想到的最好的)

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]
for item in array: array2.append (item)

或者,在这种情况下:

array2 += array

如果您要复制数组:

array2 = array[:]

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]

甚至array2.extend(array1)都可以工作。

Using elements from the list 'A' create a new list 'B' with elements, which are less than 10 使用列表“A”中的元素创建一个包含元素的新列表“B”,这些元素小于10

Option 1: 选项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: 选项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] 结果:[1,1,2,3,5,8,4,9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM