简体   繁体   English

如何计算具有特定条件的列表中的元素

[英]How to count elements inside list with specific condition

I am making combination of six number is seems easy but i need output of specific combination我正在制作六个数字的组合似乎很容易,但我需要特定组合的输出

i think i need to use count function and loop?????我想我需要使用计数功能和循环????

from itertools import combinations

comb = combinations([1, 2, 3, 4, 5, 6], 3) 
for n in list(comb):
  print (n)

Actual result give me 20 combination, but i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3,实际结果给了我 20 个组合,但我需要的代码解决方案只给我组合 n,其中 n(n1,n2,n3) n1+n2=n3,

so in my case it will be所以就我而言,它将是

(1,2,3) (1,3,4) (1,4,5) (1,5,6) (2,3,5) (2,4,6)

i need solution of code gives me only combination n where n(n1,n2,n3) n1+n2=n3我需要代码的解决方案只给我组合 n 其中 n(n1,n2,n3) n1+n2=n3

Add that as an if statement inside the for loop:将其添加为 for 循环内的if语句:

for n in comb:
    if n[0] + n[1] == n[2]:
        print (n)

Try this oneliner:试试这个oneliner:

from itertools import combinations as combs
print(list(filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3))))

Or if your want to print one combination at a time you can do:或者,如果您想一次打印一个组合,您可以执行以下操作:

from itertools import combinations as combs
for comb in filter(lambda c: c[0]+c[1]==c[2], combs(range(1,7), 3)):
    print(comb)

Another solution:另一种解决方案:

result = [(x,y,z) for (x,y,z) in combinations([1, 2, 3, 4, 5, 6], 3) if x+y==z]
print(result)

[(1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (2, 3, 5), (2, 4, 6)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM