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

我只想将列表中的每个元素除以 int。

我只想将列表中的每个元素除以 int。

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]

EDIT:

的代码给了我预期的结果:

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

但是有一个更容易 / 更快的方法来做到这一点?

287

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

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]
96

您首先尝试的方式实际上可以直接使用numpy

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

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

28
>>> 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]
13

抽象版本可以是:

import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList  = np.divide(myList, myInt)

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(530)
通过 C#弹出USB设备
上一篇
在Docker中使用SpringBootJava生成ApachePOI xlsx文件
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(82条)