我有一个清单
a=[1,2,3]
我想在此列表中执行组合(相邻数字),我希望将每个组合乘以如下
1
1 2
2
1 2 3
2 3
3
在此之后,我想执行
a) 1*1= 1
b) 1*2+2*2= 6
c) 2*2= 4
d) 1*3+2*3+3*3= 18
e) 2*3+3*3= 15
f) 3*3= 9
预期的输出是
[1,2,4,18,15,9]
这是我尝试过的代码:
def grouper(input_list, n = 2):
for i in xrange(len(input_list) - (n - 1)):
yield input_list[i:i+n]
答案 0 :(得分:1)
a = [1,2,3]
for item in [a[0:m+1] for m in range(len(a))]:
for n in range(len(item)):
result.append(item[n:])
test.append(sum([k * len(item) for k in item[n:]]))
print result
print test
<强>输出强>
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]
[1, 6, 4, 18, 15, 9]
更长篇
a = [1,2,3,4]
<强>输出强>
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
[1, 6, 4, 18, 15, 9, 40, 36, 28, 16]
简单地使用for循环
a = [1,2,3]
tmp = []
for m in range(len(a)):
tmp.append( a[0:m +1])
result = []
test = []
for item in tmp:
for n in range(len(item)):
result.append(item[n:])
test.append(sum([k * len(item) for k in item[n:]]))
print tmp
print result
print test
<强>输出强>
[[1], [1, 2], [1, 2, 3]]
[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3]]
[1, 6, 4, 18, 15, 9]
答案 1 :(得分:-1)
创建组合:
a = [1,2,3]
# create combinations
combinations = []
for i in range(len(a)):
for j in range(len(a)):
result = a[i:j+1]
if result:
combinations.append(result)
输出:
combinations [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
计算所需的值:
for values in combinations:
last_val = values[-1]
computation = ''
result = 0
for val in values:
computation += "{}*{} + ".format(val, last_val)
result += val * last_val
computation = computation[:-2] + '= {}'.format(result)
print(computation)
输出:
1*1 = 1
1*2 + 2*2 = 6
1*3 + 2*3 + 3*3 = 18
2*2 = 4
2*3 + 3*3 = 15
3*3 = 9
答案 2 :(得分:-1)
@Vikash Singh在这里提供了一个几乎的完整解决方案: 除了与组合几乎没有不匹配之外:
我设法纠正了同样的事情:
semanage permissive -d httpd_t
输出
[[1],[1,2],[2],[1,2,3],[2,3],[3]]
如果列表是 [1,2,3,4] ,输出将为:
[[1],[1,2],[2],[1,2,3],[2,3],[3],[1,2,3,4],[ 2,3,4],[3,4],[4]]
我希望这能解决OP组合的问题。