Python 板


LINE

我有一个问题 但我是新手 想好久了 写不出来 想请教各位高手 我有一列数 存在阵列里面 a[1]=x a[2]=y a[3]=z 。 。 a[n]=xxx 我要把上面的阵列 存在另一个阵列里面 变成 b[1]=x b[2]=x+y b[3]=x+y+z b[n]=x+y+z+....xxx 我该如何做呢????请大家教我.... --



※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 111.253.103.239
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1547600673.A.7B3.html
1F:推 sean50301: b[i] = [sum(a[1:i]) for i in range(0,n)] 01/16 09:20
2F:→ sean50301: b = 01/16 09:20
3F:→ sean50301: 打错 01/16 09:21
4F:→ sean50301: b = [sum(a[0:i]) for i in range(0,n)] 01/16 09:22
5F:推 adrianshum: b=[sum(x[0:i+1]) for i in (range(0, len(x))] 01/16 09:25
6F:→ adrianshum: 楼上, range 的 to index 是 exclusive 01/16 09:26
7F:推 sean50301: 对欸应该+1XD 01/16 09:27
8F:→ kiey: b.append(a[idx] if idx == 0 else b[idx-1] + a[idx]) 01/16 09:34
9F:→ chenbigdog: 谢谢楼上高手!!!!! 01/16 10:00
10F:→ chenbigdog: k大的写法,小弟看不懂...哈..不过还是很谢谢你!!!! 01/16 10:00
11F:推 yangs0618: K大的是 index是0的b直接给a0 不是的就把前一个b加上这 01/16 12:14
12F:→ yangs0618: 个index的a 有点归纳法fu 01/16 12:14
13F:→ djshen: 不要写成O(n^2)好吗.. 01/16 12:34
14F:→ djshen: 另外这写不出来不是程式问题 是国小国中数学问题 01/16 12:37
15F:推 adrianshum: 写成O(n^2) 单纯因为可以一行搞定,当然要是知道input 01/16 15:12
16F:→ adrianshum: 会很大就不会这样写。那上面那句 append 还是要配个f 01/16 15:12
17F:→ adrianshum: or loop 才行,要是要写 for loop 我觉得那就不必写得 01/16 15:12
18F:→ adrianshum: 那麽隐晦。这样写更易明白: 01/16 15:12
19F:→ adrianshum: sum=0 01/16 15:12
20F:→ adrianshum: for i in x : 01/16 15:12
21F:→ adrianshum: sum+=i 01/16 15:12
22F:→ adrianshum: y.append(sum) 01/16 15:13
23F:→ adrianshum: Oops 上一行忘了indent 01/16 15:13
24F:推 adrianshum: 其实用 itertools.accumulate 也可以一行搞定: 01/17 01:05
25F:→ adrianshum: y=list(itertools.accumulate(x, lambda a,b: a+b)) 01/17 01:06
26F:→ chenbigdog: python板充满温暖,谢谢各位!!!! 01/17 09:43







like.gif 您可能会有兴趣的文章
icon.png[问题/行为] 猫晚上进房间会不会有憋尿问题
icon.pngRe: [闲聊] 选了错误的女孩成为魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一张
icon.png[心得] EMS高领长版毛衣.墨小楼MC1002
icon.png[分享] 丹龙隔热纸GE55+33+22
icon.png[问题] 清洗洗衣机
icon.png[寻物] 窗台下的空间
icon.png[闲聊] 双极の女神1 木魔爵
icon.png[售车] 新竹 1997 march 1297cc 白色 四门
icon.png[讨论] 能从照片感受到摄影者心情吗
icon.png[狂贺] 贺贺贺贺 贺!岛村卯月!总选举NO.1
icon.png[难过] 羡慕白皮肤的女生
icon.png阅读文章
icon.png[黑特]
icon.png[问题] SBK S1安装於安全帽位置
icon.png[分享] 旧woo100绝版开箱!!
icon.pngRe: [无言] 关於小包卫生纸
icon.png[开箱] E5-2683V3 RX480Strix 快睿C1 简单测试
icon.png[心得] 苍の海贼龙 地狱 执行者16PT
icon.png[售车] 1999年Virage iO 1.8EXi
icon.png[心得] 挑战33 LV10 狮子座pt solo
icon.png[闲聊] 手把手教你不被桶之新手主购教学
icon.png[分享] Civic Type R 量产版官方照无预警流出
icon.png[售车] Golf 4 2.0 银色 自排
icon.png[出售] Graco提篮汽座(有底座)2000元诚可议
icon.png[问题] 请问补牙材质掉了还能再补吗?(台中半年内
icon.png[问题] 44th 单曲 生写竟然都给重复的啊啊!
icon.png[心得] 华南红卡/icash 核卡
icon.png[问题] 拔牙矫正这样正常吗
icon.png[赠送] 老莫高业 初业 102年版
icon.png[情报] 三大行动支付 本季掀战火
icon.png[宝宝] 博客来Amos水蜡笔5/1特价五折
icon.pngRe: [心得] 新鲜人一些面试分享
icon.png[心得] 苍の海贼龙 地狱 麒麟25PT
icon.pngRe: [闲聊] (君の名は。雷慎入) 君名二创漫画翻译
icon.pngRe: [闲聊] OGN中场影片:失踪人口局 (英文字幕)
icon.png[问题] 台湾大哥大4G讯号差
icon.png[出售] [全国]全新千寻侘草LED灯, 水草

请输入看板名称,例如:BabyMother站内搜寻

TOP