我如何进行这个简单的列表理解?
我是 python 新手,我正在尝试更好地了解列表推导式。
我什至不确定列表理解是否是我正在寻找的单词,因为我没有生成列表。但我正在做类似的事情。
这就是我想要做的:
我有一个数字列表,其长度可以被三整除。
假设我有 nums = [1, 2, 3, 4, 5, 6]
我想迭代列表并获得每组三位数的总和。 目前我正在这样做:
for i in range(0, len(nums), 3):
nsum = a + b + c for a, b, c in nums[i:i+3]
print(nsum)
我知道这是错误的,但是有办法做到这一点吗?我确信我忽略了一些可能非常简单的事情......但我想不出另一种方法来做到这一点。
I'm new to python, and I'm trying to get to know the list comprehensions better.
I'm not even really sure if list comprehension is the word I'm looking for, since I'm not generating a list. But I am doing something similar.
This is what I am trying to do:
I have a list of numbers, the length of which is divisible by three.
So say I have nums = [1, 2, 3, 4, 5, 6]
I want to iterate over the list and get the sum of each group of three digits.
Currently I am doing this:
for i in range(0, len(nums), 3):
nsum = a + b + c for a, b, c in nums[i:i+3]
print(nsum)
I know this is wrong, but is there a way to do this? I'm sure I've overlooked something probably very simple... But I can't think of another way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅
sum(iterable[, start]
)内置的,并在切片上使用它。See
sum(iterable[, start]
) builtin, and use it on slices.