目录
1. python中如何求均值?
nums = [1,2,3,4]
import numpy
numpy.mean(nums) #均值
2. python中如何求中位数?
nums = [1,2,3,4]
import numpy
numpy.median(nums) #中位数
3. python中如何求众数?
nums = [1,2,3,4]
from scipy import stats
stats.mode(nums)[0][0] #众数
4. python中如何做到输出不换行?
print('hello',end = ' ')
print('world')
#使用方法:逗号加end=' '
5. python中输出平均值之下的数字
5.1 遍历、比较、输出
import numpy as np
scores1 = [91, 95, 97, 99, 92, 93, 96, 98]
scores2 = []
average = np.mean(scores1)
for score in scores1:
if score < average:
scores2.append(score) # 少于平均分的成绩放到新建的空列表中
print('低于平均成绩的有:{}'.format(scores2))
>>>>低于平均成绩的有:[91, 95, 92, 93]
5.2 NumPy数组的操作
import numpy as np
scores1 = [91, 95, 97, 99, 92, 93, 96, 98]
average = np.mean(scores1)
scores3 = np.array(scores1)
print('低于平均成绩的有:{}'.format(scores3[scores3<average])) #NumPy数组的操作
>>>>低于平均成绩的有:[91 95 92 93] #比较5.1方法和5.2方法输出结果的不同
6. python中format格式化函数如何使用?
#使用方法:通过 {} 和 .来代替以前的 % ;不用担心用错类型码
print("{} {}".format("hello","world")) # 不设置指定位置,按默认顺序
>>>> hello world
print("{1} {0} {1}".format("hello", "world")) # 设置指定位置,可多次调用format后的数据
>>>>world hello world
print("网站名:{name}, 地址:{url}".format(name="菜鸟教程", url="www.runoob.com"))
>>>>网站名:菜鸟教程, 地址:www.runoob.com
name = "菜鸟教程"
url = "www.runoob.com"
print("网站名:{}, 地址:{}".format(name,url)) #该方法的输出结果相同
>>>>网站名:菜鸟教程, 地址:www.runoob.com
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址:{url}".format(**site)) # 通过字典设置参数,输出结果也相同
>>>>网站名:菜鸟教程, 地址:www.runoob.com
print ("{} 对应的位置是 {{0}}".format("runoob")) #可以使用大括号 {} 来转义大括号
>>>>runoob 对应的位置是 {0}
print("{:.2f}".format(3.1415926)) #数字的格式化
>>>>3.14
6.1 更多的内容☟☟▼▼☟☟
数字 | 格式 | 输出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小数点后两位 |
3.1415926 | {:+.2f} | +3.14 | 带符号保留小数点后两位 |
-1 | {:+.2f} | -1.00 | 带符号保留小数点后两位 |
2.71828 | {:.0f} | 3 | 不带小数 |
5 | {:0>2d} | 05 | 数字补零 (填充左边, 宽度为2) |
5 | {:x<4d} | 5xxx | 数字补x (填充右边, 宽度为4) |
10 | {:x<4d} | 10xx | 数字补x (填充右边, 宽度为4) |
1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00e+09 | 指数记法 |
13 | {:>10d} | 13 | 右对齐 (默认, 宽度为10) |
13 | {:<10d} | 13 | 左对齐 (宽度为10) |
13 | {:^10d} | 13 | 中间对齐 (宽度为10) |
11 | |
| 进制 |
^, <, > 分别是居中、左对齐、右对齐,后面带宽度
: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充
(空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制
%f
是格式化字符串为浮点型
,%.1f
的意思是格式化字符串为浮点型
,并保留1位小数
。