如何使用无序集合简化“for x in a for y in b for z in c ...”?

6
#!/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 进行字典求值,但这只是符号表示法。任意长度的嵌套 for 循环以及这些怪物的简化超出了 SO 的范围,更多研究请看这里。我想强调标题中的问题是开放式的,因此如果我接受一个问题,请不要被误导!


@HH,我在我的答案中添加了例如product(*d)等价于product(a,b,c)的内容。 - John La Rooy
正如所问,这个问题太宽泛了。正如所回答的那样,这是一个重复的问题,请参见https://dev59.com/HHRB5IYBdhLWcg3wuZfo。 - Karl Knechtel
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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接