如何用int划分列表中的每个元素?

时间:2011-11-23 15:37:14

标签: python

我只想将列表中的每个元素除以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)

但有更容易/更快的方法吗?

7 个答案:

答案 0 :(得分:174)

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

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 :(得分:62)

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

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

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

答案 2 :(得分:18)

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

答案 3 :(得分:8)

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

答案 4 :(得分:1)

抽象版本可以是:

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

答案 5 :(得分:0)

myInt=10
myList=[tmpList/myInt for tmpList in range(10,100,10)]

答案 6 :(得分:0)

我正在寻找一些答案,以了解大量的最快方法。因此,我发现我们可以将int转换为数组,并且它可以给出正确的结果并且速度更快。

  arrayint=np.array(myInt)
  newList = myList / arrayint

这是上述所有答案中的comparison

import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList  = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)