鱼C论坛

 找回密码
 立即注册
查看: 2742|回复: 7

[已解决]列表每三个元素求和

[复制链接]
发表于 2019-11-13 09:40:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大大,现在想要实现一个功能。
现有列表List1 = [1,2,3,4,5]

想要获得每三个元素求和所得到的值,即:

1+2+3;1+2+4;1+2+5;2+3+4; 2+3+5; 3+4+5

这个可以用for in 来实现吗?
最佳答案
2019-11-13 09:49:26
  1. from itertools import combinations as cl
  2. list1=[1,2,3,4,5]
  3. for x,y,z in cl(list1,3):
  4.     print(f'{x}+{y}+{z}={x+y+z}')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-11-13 09:49:26 | 显示全部楼层    本楼为最佳答案   
  1. from itertools import combinations as cl
  2. list1=[1,2,3,4,5]
  3. for x,y,z in cl(list1,3):
  4.     print(f'{x}+{y}+{z}={x+y+z}')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-13 09:55:30 | 显示全部楼层
  1. In [70]: from itertools import combinations

  2. In [71]: list1 = [1, 2, 3, 4, 5]

  3. In [72]: [sum(i) for i in combinations(list1, 3)]
  4. Out[72]: [6, 7, 8, 8, 9, 10, 9, 10, 11, 12]

  5. In [73]: [i for i in combinations(list1, 3)]
  6. Out[73]:
  7. [(1, 2, 3),
  8. (1, 2, 4),
  9. (1, 2, 5),
  10. (1, 3, 4),
  11. (1, 3, 5),
  12. (1, 4, 5),
  13. (2, 3, 4),
  14. (2, 3, 5),
  15. (2, 4, 5),
  16. (3, 4, 5)]
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-13 09:56:19 | 显示全部楼层
本帖最后由 raymond0385 于 2019-11-13 10:04 编辑

看錯題
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-13 10:17:44 | 显示全部楼层
本帖最后由 __mrsq__ 于 2019-11-13 11:02 编辑
  1. list1 = [1,2,3,4,5]
  2. n = len(list1)

  3. for i in range(0,n-2):
  4.     for j in range (i+1,n-1):
  5.         tem = list1[i] + list1[j]
  6.         for k in range (j+1,n):
  7.             print(list1[i],'+',list1[j],'+',list1[k],'=',tem+list1[k])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2019-11-13 15:17:24 | 显示全部楼层
本帖最后由 icewin 于 2019-11-13 17:18 编辑
  1. print("第一位",'第二位','第三位','和')
  2. for x in range(1,6):
  3.         for y in range(1,6):
  4.                 for z in range(1,6):
  5.                         print("  %d     %d     %d,   %d"%(x,y,z,x+y+z))
复制代码



如果要不重复的
  1. list1=[1,2,3,4,5]
  2. while len(list1)-3>=0:
  3.     x=list1.pop()
  4.     list2=list1[:]
  5.     while len(list2)>=2:
  6.         y=list2.pop()
  7.         for z in list2:
  8.                 print(" %d+ %d + %d = %d"%(x,y,z,x+y+z))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

头像被屏蔽
发表于 2019-11-13 16:36:40 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-11-13 17:29:50 | 显示全部楼层

这个错位取值很巧妙啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-2 00:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表