迭代 Python 中单个值和可迭代对象的混合



我正在用Python编写一个for循环,我想迭代单个对象和对象的扁平列表(或元组)的混合。

例如:

a = 'one'
b = 'two'
c = [4, 5]
d = (10, 20, 30)

我想在 for 循环中迭代所有这些。我认为这样的语法会很优雅:

for obj in what_goes_here(a, b, *c, *d):
  # do something with obj

我在itertools里找了what_goes_here,什么也没看到,但我觉得我一定错过了什么明显的东西!

发现的最接近的是链,但我想知道是否存在任何会使我的示例保持不变(仅替换what_goes_here)。

你可以这样做,但你必须使用 Python 3.5 或更高版本来扩展解包语法。将所有参数放入一个容器(如tuple),然后将该容器发送到itertools.chain

>>> import itertools
>>> a = 'one'
>>> b = 'two'
>>> c = [4, 5]
>>> d = (10, 20, 30)
>>> list(itertools.chain((a, b, *c, *d)))
['one', 'two', 4, 5, 10, 20, 30]
>>> list(itertools.chain((a, *c, b, *d)))
['one', 4, 5, 'two', 10, 20, 30]
>>> list(itertools.chain((*a, *c, b, *d)))
['o', 'n', 'e', 4, 5, 'two', 10, 20, 30]
import collections, itertools
a = 'one'
b = 'two'
c = [4, 5]
d = (10, 20, 30)
e = 12
l = [a, b, c, d, e]
newl = list(itertools.chain(*[x if isinstance(x, collections.Iterable) and not isinstance(x, str) else [x] for x in l]))

最新更新