学习python笔记(一),列表嵌套的频率统计与排序
第一次记录自己学习过程中遇到的问题,并记录与分享。
《python网络数据采集》第95页,提到了将数据清洗后进行序列统计排序的问题,但未给出代码,并且他以字典方式实现我实在看不明白。。就试着自己写了种办法
x = [[1, 2], [1, 2], [2, 3], [2, 3], [2, 3], [3, 4]]
y = [list(t) for t in set(tuple(_) for _ in x)] # 列表嵌套去重
n = [x.count(i) for i in y] # 统计频率
z = zip(y, n)
z = sorted(z, key=lambda t: t[1], reverse=True) # 按频率倒排序
print(z)
输出结果
[([2, 3], 3), ([1, 2], 2), ([3, 4], 1)]
一开始对x直接使用set函数报错
x = [[1, 2], [1, 2], [2, 3], [2, 3], [2, 3], [3, 4]]
set(x)
报错为
TypeError: unhashable type: ‘list’
查资料后发现set不能对列表去重,但是可以对元组去重,去重后再将其变为列表
x = [[1, 2], [1, 2], [2, 3], [2, 3], [2, 3], [3, 4]]
y = [list(t) for t in set(tuple(_) for _ in x)]
最后书中代码与此方法结合
import requests
from bs4 import BeautifulSoup
import re
import string
from collections import OrderedDict
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch, br',