python 列表推导式;压缩列表列表? [英] python list comprehensions; compressing a list of lists?

查看:26
本文介绍了python 列表推导式;压缩列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们.我正在尝试为问题找到最优雅的解决方案,并想知道 python 是否为我正在尝试做的事情内置了任何东西.

guys. I'm trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I'm trying to do.

我正在做的是这个.我有一个列表,A,还有一个函数 f,它接受一个项目并返回一个列表.我可以使用列表理解来转换 A 中的所有内容;

What I'm doing is this. I have a list, A, and I have a function f which takes an item and returns a list. I can use a list comprehension to convert everything in A like so;

[f(a) for a in A]

但这会返回一个列表列表;

But this return a list of lists;

[a1,a2,a3] => [[b11,b12],[b21,b22],[b31,b32]]

我真正想要的是得到扁平化的列表;

What I really want is to get the flattened list;

[b11,b12,b21,b22,b31,b32]

现在,其他语言都有了;它在函数式编程语言中传统上称为 flatmap,而 .Net 将其称为 SelectMany.python有类似的吗?有没有一种巧妙的方法可以将函数映射到列表上并将结果展平?

Now, other languages have it; it's traditionally called flatmap in functional programming languages, and .Net calls it SelectMany. Does python have anything similar? Is there a neat way to map a function over a list and flatten the result?

我试图解决的实际问题是这样的;从目录列表开始,找到所有子目录.所以;

import os
dirs = ["c:\usr", "c:\temp"]
subs = [os.listdir(d) for d in dirs]
print subs

currentliy 给了我一个列表列表,但我真的想要一个列表.

推荐答案

您可以在单个列表推导式中嵌套迭代:

You can have nested iterations in a single list comprehension:

[filename for path in dirs for filename in os.listdir(path)]

相当于(至少在功能上):

which is equivalent (at least functionally) to:

filenames = []
for path in dirs:
    for filename in os.listdir(path):
        filenames.append(filename)

这篇关于python 列表推导式;压缩列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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