鉴于这种情况,我有以下清单:
['graph_edges', ['graph_nodes'], ['graph_nodes'], ['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]]我想把它转换成:
['graph_edges', 'graph_nodes', 'graph_nodes', 'graph_edges2', 'graph_nodes2', 'graph_nodes2']
# I would list(set(thislist)) afterwardsThere is a ton of solutions out there already,但奇怪的是,就我的情况而言,我无法做任何有意义的事情:
from functools import reduce
import operator
reduce(operator.concat,['graph_edges', ['graph_nodes'], ['graph_nodes'], ['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]])
*** TypeError: can only concatenate str (not "list") to str同样适用于sum
sum(['graph_edges', ['graph_nodes'], ['graph_nodes'], ['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]], [])这艘客轮开得太多了:
> [item for sublist in ['graph_edges', ['graph_nodes'], ['graph_nodes'], ['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]] for item in sublist]
['g', 'r', 'a', 'p', 'h', '_', 'e', 'd', 'g', 'e', 's', 'graph_nodes', 'graph_nodes', 'graph_edges2', ['graph_nodes2'], ['graph_nodes2']]或者使用迭代工具:
>!list(itertools.chain(*lol))
['g', 'r', 'a', 'p', 'h', '_', 'e', 'd', 'g', 'e', 's', 'graph_nodes', 'graph_nodes', 'graph_edges2', ['graph_nodes2'], ['graph_nodes2']]免责声明:我在ipdb中尝试过这些,所以总是有可能出现错误
我目前(不工作)和非常不满意的解决办法如下:
retlist= []
dedefined=['graph_edges', ['graph_nodes'], ['graph_nodes'], ['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]]
for element in dedefined:
if isinstance(element,list):
retlist+=self.getSingleElement(element)
else:
retlist.append(element)
return list(set(retlist))
@classmethod
def getSingleElement(cls,element):
if isinstance(element,list):
return cls.getSingleElement(*element)
else: return element当element到达['graph_edges2', ['graph_nodes2'], ['graph_nodes2']]时,它是失败的,但我无法想到有意义的东西。我可以创建一个生成器来生成新的值,而不是返回,或者迭代每个元素,并使其成为一个可以被分解的列表。但这些想法对我来说都没有说服力
发布于 2022-04-06 17:00:42
您需要使用递归来解释列表可以任意嵌套的深层次这一事实:
def flatten(lst):
result = []
for item in lst:
# You can use:
# if not isinstance(item, list):
# if you have other items besides integers in your nested list.
if isinstance(item, str):
result.append(item)
else:
result.extend(flatten(item))
return result这一产出如下:
['graph_edges', 'graph_nodes', 'graph_nodes',
'graph_edges2', 'graph_nodes2', 'graph_nodes2']发布于 2022-04-06 17:02:15
def flatten(array):
flat = []
for member in array:
if isinstance(member, (tuple, list)):
flat.extend(flatten(member))
else:
flat.append(member)
return flathttps://stackoverflow.com/questions/71770712
复制相似问题