不使用itertools重写只是简单的python

时间:2015-06-15 00:02:27

标签: python

如何重写这段代码,以便它不使用itertools(只是简单的python可能在多行中,而不使用yield)?

list(itertools.chain.from_iterable([node] * (indeg[node] + 1) for node in graph.keys()))

1 个答案:

答案 0 :(得分:0)

在此上下文中itertools.chain仅用作展平嵌套列表(或生成器)的方法

In [266]: keys
Out[266]: [0, 1, 2, 3]

In [267]: indeg=[6,4,2,0]

In [269]: ll=[[node] * (indeg[node] + 1) for node in keys]

In [270]: ll
Out[270]: [[0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2], [3]]

一个简单的循环可以执行相同的展平:

In [271]: result=[]
In [272]: for i in ll: result.extend(i)
In [273]: result
Out[273]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]

我不知道像表达这样能够达到同样目的的理解。虽然chain的便利性可能已经将其重新编入历史,但Python的食谱可能会有这个。

reduce add给出一行分隔符:

In [285]: import operator
In [286]: reduce(operator.add, ll, [])
Out[286]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]

这就像重复result += i一样,列表与extend相同。

根据评论工作:

In [289]: [j for i in ll for j in i]
Out[289]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]

或原作为双重迭代:

In [290]: [j for node in keys for j in [node] * (indeg[node] + 1)]
Out[290]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]