# 如何优雅的处理python list问题

• 167

``````# example:
tmp = ['0-0', ['0-1-0', '0-1-5'], ['0-2-0', '0-2-1', '0-2-2'], ['3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5'], '4-0', '4-1', '5-0', '5-1']
# to:
des = ['0-0', '0-1-0', '0-1-5', '0-2-0', '0-2-1', '0-2-2', '3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5', '4-0', '4-1', '5-0', '5-1']``````

1. 实际问题是很大量的数, 如何不增加额外`list`的情况下处理? (需要内存控制)

2. 维度已知, 二维

3. 若维度增加, 应该如何处理?

4 个回答
ferstar
• 1.2k
✓ 已被采纳

py3.x

``````import collections

def list_exp1(iterable):
for el in iterable:
if not isinstance(el, str) and isinstance(el, collections.Iterable):
yield from list_exp(el)
else:
yield el``````

py2.x

``````import collections

def list_exp1(iterable):
for el in iterable:
if not isinstance(el, basestring) and isinstance(el, collections.Iterable):
for subel in el:
yield subel
else:
yield el``````

``````def list_exp(lst):
_lst = []
for i in lst:
if not isinstance(i, list):
_lst.append(i)
else:
_lst += list_exp(i)
return _lst``````

``````# 二维
tmp = ['0-0', ['0-1-0', '0-1-5'], ['0-2-0', '0-2-1', '0-2-2'], ['3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5'], '4-0', '4-1', '5-0', '5-1']
print(list_exp(tmp))
['0-0', '0-1-0', '0-1-5', '0-2-0', '0-2-1', '0-2-2', '3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5', '4-0', '4-1', '5-0', '5-1']

# N维
tmp = ['0-0', ['0-1-0', '0-1-5', ['0-1-0', '0-1-5'], ['0-0', ['0-1-0', '0-1-5', ['0-1-0', '0-1-5']]]]]
print(list_exp(tmp))
['0-0', '0-1-0', '0-1-5', '0-1-0', '0-1-5', '0-0', '0-1-0', '0-1-5', '0-1-0', '0-1-5']``````