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

后端 未结 7 2135
野的像风
野的像风 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:31

    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)
    
    0 讨论(0)
提交回复
热议问题