在python中迭代单个值和可重用项的混合

在python中迭代单个值和可重用项的混合,python,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中查找这里发生了什么,但我什么也没看到,但我觉得我肯定错过了一些明显的东西 我找到的最

我正在用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
中查找
这里发生了什么
,但我什么也没看到,但我觉得我肯定错过了一些明显的东西


我找到的最接近的是chain,但我想知道是否有任何东西会使我的示例保持不变(仅替换
此处的内容)。

您可以这样做,但必须使用Python 3.5或更高版本来扩展解包语法。将所有参数放入一个容器(如
元组
),然后将该容器发送到
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]

您的迭代输出是什么?您将遇到的问题是字符串是可编辑的,因此您的字符串很可能被拆分为单个字符。我想您可能需要为此编写自己的函数。
l=[a,b,c,d]
list(itertools.chain(*[x if not isinstance(x,str)else[x]for x in l])
正如@AlJohri在列表理解中所做的那样,您可以检查对象类型。@AlJohri:他说了吗?哪里我只能看到一个,但我想知道是否有任何东西会使我的示例保持不变(只替换此处的内容)。
>>> 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]