如何使这个简单的列表理解? [英] How do I make this simple list comprehension?

查看:47
本文介绍了如何使这个简单的列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我试图更好地了解列表理解.
我什至不确定我是否要使用列表理解这个词,因为我没有生成列表.但是我正在做类似的事情.

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.

这就是我想要做的:

我有一个数字列表,其长度可以被三整除.

I have a list of numbers, the length of which is divisible by three.

所以说我有nums = [1, 2, 3, 4, 5, 6] 我想遍历该列表并获取每组三位数的总和. 目前,我正在这样做:

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.

推荐答案

请参见 )内置,并在切片上使用它.

See sum(iterable[, start]) builtin, and use it on slices.

总和从左到右开始,然后是一个可迭代项,然后返回总计.开始的默认值是0.可迭代的项通常是数字,不允许为字符串.

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings.

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

这篇关于如何使这个简单的列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆