如何用无序简化“for x in a for y in b for z in c ...”?
-
26-09-2019 - |
题
#!/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 ...
, , IE。任意数量的结构,写作 product(a,b,c,...)
很麻烦。假设您有一个列表列表,例如 d
在上面的例子中。你能简单点吗?Python 让我们做 unpacking
和 *a
对于列表和字典评估 **b
但这只是符号。任意长度的嵌套 for 循环和此类怪物的简化超出了 SO 的范围,有待进一步研究 这里. 。我想强调的是,标题中的问题是开放式的,所以如果我接受问题,请不要被误导!
解决方案
>>> 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))
其他提示
尝试这个
>>> 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#']
不隶属于 StackOverflow