如何将列表中的每个元素除以int?

2024-04-25 22:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想把列表中的每个元素除以一个整数

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = myList/myInt

这是错误:

TypeError: unsupported operand type(s) for /: 'list' and 'int'

我明白我为什么会收到这个错误。但我很沮丧,因为我找不到解决办法。

也尝试过:

newList = [ a/b for a, b in (myList,myInt)]

错误:

ValueError: too many values to unpack

预期结果:

newList = [1,2,3,4,5,6,7,8,9]


编辑:

下面的代码给出了我的预期结果:

newList = []
for x in myList:
    newList.append(x/myInt)

但是有没有一种更简单/更快的方法来做到这一点呢?


Tags: andin元素列表fortype错误整数
3条回答
>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]

您第一次尝试的方式实际上可以直接使用numpy

import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt

如果你用长列表来做这些操作,特别是在任何科学计算项目中,我真的建议你使用numpy。

惯用的方法是使用列表理解:

myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [x / myInt for x in myList]

或者,如果需要保留对原始列表的引用:

myList[:] = [x / myInt for x in myList]

相关问题 更多 >