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

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

459222 次浏览

The idiomatic way would be to use list comprehension:

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

or, if you need to maintain the reference to the original list:

myList[:] = [x / myInt for x in myList]
>>> 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]
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]

The way you tried first is actually directly possible with numpy:

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

If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise using numpy.

The abstract version can be:

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

I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.

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

This a comparison of all answers above

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)
list = [2,4,8]
new_list = [x//2 for x in list]
print(new_list)

Output:

[1, 2, 4]