将取模应用于python列表的所有元素,并获得一些正确的一些不正确的元素 [英] Applying modulo to all elements of a python list and getting some correct some incorrect elements

查看:18
本文介绍了将取模应用于python列表的所有元素,并获得一些正确的一些不正确的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个函数,以减少列表模 3 的所有元素.这是我所拥有的:

I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:

def reduceMod3(l):
    for i in l:
        l[i] = l[i] % 3
    return l

当我在L = [1,2,3,4,5,6,7,8,9]上调用此函数时,我得到:

when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:

L = [1, 2, 0, 4, 2, 6, 1, 8, 0]

这是为什么?我想弄清楚,但我很着急.谢谢.

Why is this? I am trying to figure it out but I'm in a rush. Thanks.

推荐答案

在l中为i编写时,您正在访问列表的每个元素,而不是索引.相反,您应该写

When you write for i in l, you are accessing each element of the list, not the index. Instead, you should write

for i in range(len(l)):

您还可以通过列表理解来解决此问题:

You can also solve this with a list comprehension:

return [item % 3 for item in l]

这篇关于将取模应用于python列表的所有元素,并获得一些正确的一些不正确的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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