简体   繁体   English

如何使这个简单的列表理解?

[英]How do I make this simple list comprehension?

I'm new to python, and I'm trying to get to know the list comprehensions better. 我是python的新手,我正在努力更好地了解列表推导。
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. 所以说我有nums = [1, 2, 3, 4, 5, 6]我想迭代列表并获得每组三位数的总和。 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. 我确信我忽略了一些非常简单的事情......但我想不出另一种方法可以做到这一点。

See sum(iterable[, start] ) builtin, and use it on slices. 请参见sum(iterable[, start] builtin,并在切片上使用它。

Sums start and the items of an iterable from left to right and returns the total. Sums从左到右开始和可迭代的项目并返回总数。 start defaults to 0. The iterable's items are normally numbers, and are not allowed to be strings. start默认为0. iterable的项通常是数字,不允许是字符串。

>>> nums
[1, 2, 3, 4, 5, 6]
>>> [sum(nums[i:i+3]) for i in  range(0, len(nums),3)]
[6, 15]
>>> 
import itertools

nums = [1, 2, 3, 4, 5, 6]

print [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]
nums = [1, 2, 3, 4, 5, 6]
map(sum, itertools.izip(*[iter(nums)]*3))

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

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