Python 一行“for"表达 [英] Python one-line "for" expression

查看:40
本文介绍了Python 一行“for"表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否需要 lambda 或其他东西.但是,我仍然需要以下内容:

我有一个 array = [1,2,3,4,5].例如,我需要将此数组放入另一个数组中.但是写在一行中.

 用于数组中的项目:array2.append(item)

我知道这完全有可能遍历项目并使其成为一行.但是谷歌搜索和阅读手册对我没有多大帮助......如果你能给我一个提示或命名这个东西以便我能找到它是什么,我真的很感激.

更新:让我们这样说:array2 = 一些花哨的表达式,可以从第一个表达式中获取所有数据

(这个例子不是真的.我只是想遍历不同的数据块,但这是我能想到的最好的)

解决方案

您要查找的关键字是 列表推导:

<预><代码>>>>x = [1, 2, 3, 4, 5]>>>y = [2*a for a in x if a % 2 == 1]>>>打印(y)[2, 6, 10]

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)

解决方案

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]

这篇关于Python 一行“for"表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆