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

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

问题描述

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

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

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

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.

更新:让我们这样说: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)

推荐答案

您要查找的关键字是列表理解:

>>> 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天全站免登陆