如何在Python中最佳地将多维列表转换为单个项目列表? [英] How to optimally turn a multidimentional list into a single list of items in Python?
问题描述
可能的重复项:
从以下列表中的列表中删除一个列表Python
用Python整理的(不规则的)列表列表 >
Possible Duplicates:
Making a flat list out of list of lists in Python
Flatten (an irregular) list of lists in Python
输入一个列表,例如:[1,2,[3,4,[5,6,7,[8]]],[9],10]
Input a list such as: [1,2,[3,4,[5,6,7,[8]]],[9],10]
所需的输出:[1,2,3,4,5,6,7,8,9,10]
Desired output: [1,2,3,4,5,6,7,8,9,10]
当前,我具有以下递归函数:
Currently I have the following recursive function:
def fix_list( li , l = [] ):
for i in li:
try:
len( i )
fix_list( i, l )
except:
l.append( i )
return l
我觉得try/except捕获有点花哨和缓慢,我想知道是否有更好/更优化的方法来执行此任务.非常感谢所有输入.
I feel like the try/except catch is a little gimmicky and slow, and I'm wondering if there is a better/more optimized way to perform this task. All input is greatly appreciated.
推荐答案
这里是一个迭代版本(最初是由Artsiom Rudzenka启发的),它使用切片分配在适当的位置修改了列表,而不是在每次通过时都创建一个新列表.有趣的是,只需要遍历该列表!我对enumerate()
的使用有点不合常规.我用它来跟踪列表中的索引,该索引在迭代时可能会不断增长,但实际上并没有使用实际的列表项.
Here is an iterative version (originally inspired by Artsiom Rudzenka's) that modifies the list in place using slice assignment rather than creating a new list on each pass. Interestingly, only one pass through the list is needed! My use of enumerate()
is a little unorthodox; I use it to keep track of an index into a list that may be growing as I iterate over it, but don't actually use the actual list item.
def flattened(items, seqtypes=(list, tuple)):
items = items[:] # we will return a copy; remove to mutate original
for i, _ in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
return items
print flattened([1,2,[3,4,[5,6,7,[8]]],[9],10])
发电机版本:
def flattener(items, seqtypes=(list, tuple)):
items = items[:]
for i, _ in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
yield items[i]
print list(flattener([1,2,[3,4,[5,6,7,[8]]],[9],10]))
这里是具有flatten()
方法的list
子类.像sort()
和reverse()
方法一样,这会使列表变异并返回None
.
Here is a list
subclass that has a flatten()
method. Like the sort()
and reverse()
methods, this mutates the list and returns None
.
class listy(list):
def flatten(self, seqtypes=(list, tuple)):
for i, _ in enumerate(self):
while isinstance(self[i], seqtypes):
self[i:i+1] = self[i]
lst = listy([1,2,[3,4,[5,6,7,[8]]],[9],10])
lst.flatten()
print lst
我从原始版本中大大简化了此操作.但是,我看到问题已经解决.
I simplified this pretty significantly from my original version. However, I see the question has been closed.
这篇关于如何在Python中最佳地将多维列表转换为单个项目列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!