Python列表解析;压缩列表的列表? [英] python list comprehensions; compressing a list of lists?
问题描述
人。我试图找到一个问题的最优雅的解决方案,并想知道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]
但是这会返回一个列表列表; p>
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?
我试图解决的实际问题是:从目录列表开始,查找所有子目录。所以;
The actual problem I'm trying to solve is this; starting with a list of directories, find all the subdirectories. so;
import os
dirs = ["c:\\usr", "c:\\temp"]
subs = [os.listdir(d) for d in dirs]
print subs
currentliy给了我一个清单列表,但我真的很想要一个清单。
currentliy gives me a list-of-lists, but I really want a list.
推荐答案
您可以在单个列表解析中嵌套迭代:
You can have nested iterations in a single list comprehension:
[filename for path in dirs for filename in os.listdir(path)]
这篇关于Python列表解析;压缩列表的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!