2017-02-17 9 views
2

リストの要素に他のすべての要素を掛けたい。例えばリストの要素と同じリスト内の他の要素との乗算

def product(a,b,c): 
    return (a*b, a*c, a*b*c) 

私はこの

def product(*args): 
    list = [] 
    for index,element in enumerate(args): 
     for i in args: 
      if (args[index]*i) not in list: 
       list.append(args[index]*i) 
    return list 

を行っているが、これは私がそこにa*ab*bc*cビットを望んでいないなど、私に[a*a, a*b,a*c, b*b]を与えます。

ここ
+1

['itertools.combinations'](https://docs.python.org/2/library/itertools.html#itertools.combinations)は、あなたが望むものでなければなりません – Hamms

+1

最初の要素を複数にしたいだけですか?または、要素を最初に指定し、次に複数の要素を他の要素と重複させたいとしますか? – hzm

+0

@ハルジあなたはb * cをしたいですか? – PrestonH

答えて

0

あなたが平等のためにチェックすることができ

if (args[index]*i) not in list and args[index] != i: 
0

itertools is your friend

from itertools import combinations 
from functools import reduce, partial 
from operator import mul 

# Make a sum-like function for multiplication; I'd call it product, 
# but that overlaps a name in itertools and our own function 
multiplyall = partial(reduce, mul) 

def product(*args): 
    # Loop so you get all two elements combinations, then all three element, etc. 
    for n in range(2, len(args) + 1): 
     # Get the combinations for the current combo count 
     for comb in combinations(args, n): 
      # Compute product and yield it 
      # yielding comb as well just for illustration 
      yield comb, multiplyall(comb) 

だけゆっくり要素によって、リストの要素を構築し、呼び出し側が望んでいるならば、それは本当に(ジェネレータ関数でなければなりません戻っています率直に言って、ほぼすべての機能ので、私は、それジェネレータ関数作らリストは、単にmylist = list(generatorfunc(...)))、多くの引数が渡されたときに主メモリを吹き飛ばすことなく繰り返し使用することが容易になります。

使用例:

>>> for pieces, prod in product(2, 3, 4): 
     print ' * '.join(map(str, pieces)), '=', prod 

出力:

2 * 3 = 6 
2 * 4 = 8 
3 * 4 = 12 
2 * 3 * 4 = 24 
0

ので値は、あなたがすべてとのみ、これらの製品が欲しい2, 3, 4, 5ある場合:

2*3=6, 2*4=8, 2*5=10, 2*3*4=24, 2*3*5=30, 2*4*5=40, 2*3*4*5=120 

これは、3, 4, 5のすべての組み合わせを取ってから、それに2を掛け合わせることを意味します。 itertoolsモジュールはcombinations機能を有しており、reduceは、計算を行うためにoperator.mulと組み合わせて使用​​することができます。

def product(first, *other): 
    for n in range(1, len(other) + 1): 
     for m in combinations(other, n): 
      yield reduce(mul, m, first) 

list(product(2, 3, 4, 5)) 

出力:

[6, 8, 10, 24, 30, 40, 120] 
0

はあなたのリストには[2, 3, 4, 2]のような重複した要素を、持っていますか?

れていない場合は、ここでは1つのライナーです:数字で、

a = ['a1','a2','a3'] 

lsta = [[x+y for y in [z for z in a if z != x]] for x in a] 
lsta 

[['a1a2', 'a1a3'], ['a2a1', 'a2a3'], ['a3a1', 'a3a2']] 

そして、ここで:パターンを説明するためのタグと

まず、

a =[2,3,4,5] 

print [[x*y for y in [z for z in a if z != x]] for x in a] 

[[6, 8, 10], [6, 12, 15], [8, 12, 20], [10, 15, 20]] 

かあなたが望むならば、製品の合計:

a =[2,3,4,5] 

print [sum([x*y for y in [z for z in a if z != x]]) for x in a] 

[24, 33, 40, 45] 

リストに重複がある場合は、より複雑になります。最初のオカレンスと2の2回目の出現を別々に計算したいのですか(両方の値が同じになってもいくつかの目的のために必要な場合があります)。

関連する問題