「for x in a、for y in b、for z in c …」を順序なしで簡略化するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/4613481

質問

#!/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 でやってみましょう 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#']
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top