How do you divide each element in a list by an int?

后端 未结 7 2134
野的像风
野的像风 2020-12-04 08:02

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

相关标签:
7条回答
  • 2020-12-04 08:10

    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)
    
    0 讨论(0)
  • 2020-12-04 08:13

    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]
    
    0 讨论(0)
  • 2020-12-04 08:15
    myList = [10,20,30,40,50,60,70,80,90]
    myInt = 10
    newList = [i/myInt for i in myList]
    
    0 讨论(0)
  • >>> 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]
    
    0 讨论(0)
  • 2020-12-04 08:19
    myInt=10
    myList=[tmpList/myInt for tmpList in range(10,100,10)]
    
    0 讨论(0)
  • 2020-12-04 08:25

    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.

    0 讨论(0)
提交回复
热议问题