如何简化“for x in a for y in b for z in c ...”的无序版本?
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it?
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# >>> c=['#']
# >>> print([x+y+z for x in a for y in b for z in c])
# ['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
#
# The same works with sets as well
# >>> a
# set(['a', 'c', 'b'])
# >>> b
# set(['1', '2'])
# >>> c
# set(['#'])
#
# >>> print([x+y+z for x in a for y in b for z in c])
# ['a1#', 'a2#', 'c1#', 'c2#', 'b1#', 'b2#']
#BROKEN TRIALS
d = [a,b,c]
# TRIAL 2: trying to simplify the "assignments", not sure of the term
# but see the change to the abve
# print([x+y+z for x, y, z in zip([x,y,z], d)])
# TRIAL 3: simplifying TRIAL 2
# print([x+y+z for x, y, z in zip([x,y,z], [a,b,c])])
[更新] 有一个问题没有提到,如果你真的有 for x in a for y in b for z in c ...
这样的情况,也就是说有很多层的结构,写 product(a,b,c,...)
会很麻烦。假设你有一个列表的列表,比如上面例子中的 d
。有没有更简单的方法呢?Python 允许我们用 *a
来展开列表,用 **b
来处理字典,但这只是语法上的写法。对于任意长度的嵌套循环和简化这些复杂结构的问题,超出了 StackOverflow 的讨论范围,想要深入了解可以去 这里。我想强调的是,标题中的问题是开放式的,所以如果我接受了一个问题,不要误解!
2 个回答
12
试试这个
>>> import itertools
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> print [ "".join(res) for res in itertools.product(a,b,c) ]
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
8
>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_things))
编辑:
你可以把产品用在很多事情上,就像你想要的那样。