【python】实现list除以⼀个数
⽂章⽬录
list如何除以⼀个数,有如下两种⽅法:
import random
my_list =[random.randint(0,100)for x in range(10)]
print(my_list)
my_list /=10
print(new_list)
如果直接使⽤ my_list除以⼀个数,会提⽰TypeError: unsupported operand type(s) for /=: 'list' and 'int',对应的解决⽅法如下新建⼀个list,存放数据
下⾯的核⼼为:new_list = [x/10 for x in my_list]
import random
my_list =[random.randint(0,100)for x in range(10)]
print("before:", my_list)
new_list =[x/10for x in my_list]
print("after :", my_list)
print("new :", new_list)
代码对应的结果为:
当然了,这⾥可以把结果仍然赋值给my_list,不过位置已经改变,程序如下:
import random
my_list =[random.randint(0,100)for x in range(10)]
print("before:",id(my_list),"value:", my_list)
random pythonmy_list =[x/10for x in my_list]
print("after :",id(my_list),"value:", my_list)
输出结果为:
before: 4748790984 value: [31, 14, 11, 97, 58, 90, 100, 80, 35, 38]
after : 4748791112 value: [3.1, 1.4, 1.1, 9.7, 5.8, 9.0, 10.0, 8.0, 3.5, 3.8]
使⽤numpy – np.divide
import random
import numpy as np
arr = np.array([random.randint(0,100)for x in range(10)])
print("before:",id(arr),"value:", arr)
arr = np.divide(arr,10)
print("after :",id(arr),"value:", arr)
输出结果为:
before: 4763023680 value: [18 14 56 22 6 64 99 24 16 97]
after : 4763260608 value: [1.8 1.4 5.6 2.2 0.6 6.4 9.9 2.4 1.6 9.7]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论