我有一个包含5个元素的列表,x + 2,x ^ 3 + x ^ 2 + x + 2,x ^ 3 + x ^ 2 + 2,x ^ 3 + 2x ^ 2 + 2x + 2,x ^ 3 + 2×2 +。我试图获得一个包含(x+2)(x^3+x^2+x+2), (x+2)(x^3+x^2+x+2)(x^3+x^2+2)
等元素的大清单。一个元素乘以其他四个元素以获得新元素。我知道的唯一方法是使用For循环来做它,但它没有给我正确的列表。这就是我所拥有的:
L = ['x+2','x^3+x^2+x+2','x^3+x^2+2','x^3+2x^2+2x+2','x^3+2x+2']
for i in range(0,len(L)):
for j in range(1,len(L)):
for k in range(2,len(L)):
for l in range(3,len(L)):
for m in range(4,len(L)):
print L[i],L[j],L[k],L[l],L[m]
我有很多重复元素,我想知道如何在生成列表时避免使用这些重复元素。谁能告诉我怎么做?
答案 0 :(得分:3)
您可以使用combinations
函数获取列表的所有组合:
from itertools import combinations
result = []
for i in range(1,len(L)):
result.append(list(combinations(L,i))
result # [[('x+2',), ('x^3+x^2+x+2',), ('x^3+x^2+2',), ('x^3+2x^2+2x+2',), ('x^3+2x+2',)], [('x+2', 'x^3+x^2+x+2'), ('x+2', 'x^3+x^2+2'), ('x+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2'), ('x^3+x^2+x+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+x+2', 'x^3+2x+2'), ('x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+2', 'x^3+2x+2'), ('x^3+2x^2+2x+2', 'x^3+2x+2')], [('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2')], [('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+x+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2'), ('x^3+x^2+x+2', 'x^3+x^2+2', 'x^3+2x^2+2x+2', 'x^3+2x+2')]]
答案 1 :(得分:1)
您正在寻找的词是排列
Python在itertools包中有that ability included