清单理解中的总和?
这是我的代码
def width2colspec(widths):
tupleback = []
a=0
for w in widths:
b=a+w
tupleback.append((a,a+w))
a=b
return tupleback
:
widths=[15,9,50,10]
width2colspec(widths)
结果:(
[(0, 15), (15, 24), (24, 74), (74,84)]
第一个始终必须是零)
它有效的,而所有(也许不是很优雅)
我试图将其转换为一个列表理解一个衬里,但我无法使其正常工作,我得到的是这个。
widths=[15,9,50,10]
colspecs=list((widths[i],widths[i]+widths[i+1]) for i in range(len(widths)-1))
结果:(
[(0, 15), (15, 24), (9, 59), (50,60)]
它不维护循环的总和槽)
所以我的问题是,有可能吗?
this is my code
def width2colspec(widths):
tupleback = []
a=0
for w in widths:
b=a+w
tupleback.append((a,a+w))
a=b
return tupleback
eg:
widths=[15,9,50,10]
width2colspec(widths)
Result:
[(0, 15), (15, 24), (24, 74), (74,84)]
(first one always has to be a zero)
It works and all(maybe not very elegant tho)
To practice I tried to convert it into a list comprehension one liner but i couldn't make it work, closest i got was this.
widths=[15,9,50,10]
colspecs=list((widths[i],widths[i]+widths[i+1]) for i in range(len(widths)-1))
result:
[(0, 15), (15, 24), (9, 59), (50,60)]
(its not maintaining the sum trough the loop)
So my question is, is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您 can 将其作为纯粹的列表理解,但它涉及很多重新计算,因此我不建议这样实际这样做。
首先构建所有总和的列表(请注意,这是一遍又一遍地重新点击相同的数字,因此它的效率不如您的原始代码,而原始代码保持了运行总和):
然后迭代以生成您的元组列表:
请注意,我们现在重新计算所有这些总和 ,因为我们没有将原始列表分配给变量。
You can do this as a pure list comprehension, but it involves a lot of re-computation, so I wouldn't recommend actually doing it this way.
Start by building a list of all the sums (note that this is re-summing the same numbers over and over, so it's less efficient than your original code that keeps a running sum):
and then iterate over that to produce your list of tuples:
Note that we're now re-computing all those sums again because we didn't assign the original list to a variable.
如果您使用Python 3.8或更高版本,则可以使用分配表达式(使用Walrus Operator
:=
)在单个列表理解中执行此操作。我是通过默认参数初始化的来“作弊”,但这并不是严格的(我只是想让它成为“单线”)。老实说,我没有发现令人困惑。
If you're using Python 3.8 or later, you can use an assignment expression (utilizing the walrus operator
:=
) to do this in a single list comprehension. I'm "cheating" a little by initializinglast
via a default argument, but this isn't strictly necessary (I just wanted to make it a "one-liner").I don't find it that confusing, to be honest.