问题:如何将列表中的每个元素除以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]
编辑:
以下代码给了我预期的结果:
newList = []
for x in myList:
newList.append(x/myInt)
但是,有没有更容易/更快的方法来做到这一点?
I just want to divide each element in a list by an int.
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = myList/myInt
This is the error:
TypeError: unsupported operand type(s) for /: 'list' and 'int'
I understand why I am receiving this error. But I am frustrated that I can’t find a solution.
Also tried:
newList = [ a/b for a, b in (myList,myInt)]
Error:
ValueError: too many values to unpack
Expected Result:
newList = [1,2,3,4,5,6,7,8,9]
EDIT:
The following code gives me my expected result:
newList = []
for x in myList:
newList.append(x/myInt)
But is there an easier/faster way to do this?
回答 0
惯用的方法是使用列表理解:
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]
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]
回答 1
实际上,您首先可以使用numpy直接尝试:
import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt
如果您使用长列表进行此类操作,尤其是在任何类型的科学计算项目中,我都会建议您使用numpy。
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.
回答 2
>>> 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 = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
回答 3
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]
myList = [10,20,30,40,50,60,70,80,90]
myInt = 10
newList = [i/myInt for i in myList]
回答 4
抽象版本可以是:
import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList = np.divide(myList, myInt)
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)
回答 5
myInt=10
myList=[tmpList/myInt for tmpList in range(10,100,10)]
myInt=10
myList=[tmpList/myInt for tmpList in range(10,100,10)]