python 茎叶图

时间:2024-03-04 17:59:47

引例:

R 茎叶图

data <- c(1, 35, 57, 40, 73, 82, 68, 69, 52, 1, 23, 35, 55, 65, 48, 93, 59, 87, 2, 64)
stem(data)

 

1、python 实现

from itertools import groupby

data = (1, 35, 57, 40, 73, 82, 68, 69, 52, 1, 23, 35, 55, 65, 48, 93, 59, 87, 2, 64)
data = sorted([str(e) for e in data])     # 数据转换

# k 和 h 分别为每个数值的十位数字和个位数字的字符形式
for k, g in groupby(data, key=lambda x: int(x) // 10):
    lst = map(str, [int(h) % 10 for h in list(g)])
    print (k, \'|\', \' \'.join(lst))

效果: