hhh*_*hhh 6 python list-comprehension cartesian-product unordered
#!/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])])
Run Code Online (Sandbox Code Playgroud)
[更新]遗漏了一件事,如果你真的拥有for x in a for y in b for z in c ...,比如arbirtary数量的结构,写作product(a,b,c,...)是麻烦的.假设您有一个列表列表,例如d上例中的列表.你能简单一点吗?Python中让我们做unpacking与*a列表和与词典的评价**b,但它仅仅是符号.任意长度的嵌套for循环和这些怪物的简化都超出了SO,这里需要进一步研究.我想强调标题中的问题是开放式的,所以如果我接受一个问题,不要误入歧途!
yan*_*ost 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#']
Run Code Online (Sandbox Code Playgroud)
>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
Run Code Online (Sandbox Code Playgroud)
编辑:
你可以在一堆你喜欢的东西上使用产品
>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_things))
Run Code Online (Sandbox Code Playgroud)