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


154

我只想将一个列表中的每个元素都用一个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]


编辑:

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

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

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

Answers:


233

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

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]

1
给定静态列表大小,这两种方法中的任何一种都会比[mylist [0] / myint,mylist [1] / myint]快吗?
2015年

7
@ user1938107几乎可以肯定不是,但这也是您应避免的微优化类型。
soulcheck'Mar

75

实际上,您首先可以使用numpy直接尝试:

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

如果您使用长列表进行此类操作,尤其是在任何类型的科学计算项目中,我都会建议您使用numpy。


4
我知道这是一个旧的答复,但对于仍在阅读它的任何人:请记住,在使用numpy.array时,应指定例如loat的类型numpy.array([10,20,30,40,50,60,70,80,90], dtype='f')。否则,除以3只会得到3而不是3.333。.–
理查德·布嫩

3
@RichardBoonen在这种情况下,OP想要进行int除法,但是如果您要进行float除法,那么您是对的,您必须将类型指定为numpy。或在列表中添加一个浮动内容:numpy.array([10.,20,30,40,50,60,70,80,90])
silvado

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

在这种情况下,您认为map比列表理解要好吗?我只是想知道我会去理解列表,因为它更易于阅读。
Andrew Cox

@AndrewCox我更喜欢map(来自非python背景)。列表理解对我来说似乎也比较干净,因此您可能应该这样做。
Dogbert 2011年

您知道这是否比灵魂检查和berkantk发布的解决方案快?
Casa

@Casa:有人在stackoverflow.com/q/1247490上对此进行了测试。结论似乎是,在这种情况下,列表理解会获胜。
布莱恩(Brian)

4
现在map()返回一个地图对象,因此,如果要列表,则必须明确地说出list()。因此,在这种情况下:newList = list(map(lambda x: x/myInt, myList))
robertmartin8

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

6

抽象版本可以是:

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.