- 论坛徽章:
- 0
|
Python 版本
我用小數據來演示, 把人名和流量放進 dictionary, 打印第三大流量值
- $ cat test.txt
- peter|23123123|2018-10-01|107
- peter|23123123|2018-10-01|100
- peter|23123123|2018-10-01|101
- peter|23123123|2018-10-01|99
- peter|23123123|2018-10-01|105
- peter|23123123|2018-10-01|88
- peter|23123123|2018-10-01|121
- peter|23123123|2018-10-01|76
- mary|23123123|2018-10-01|12
- mary|23123123|2018-10-01|15
- mary|23123123|2018-10-01|18
- mary|23123123|2018-10-01|50
- mary|23123123|2018-10-01|22
- mary|23123123|2018-10-01|11
- $ python test.py
- peter
- ('Original list: ', ['107', '100', '101', '99', '105', '88', '121', '76'])
- ('Sorted list: ', ['121', '107', '105', '101', '100', '99', '88', '76'])
- ('The third in the list: ', '105')
- mary
- ('Original list: ', ['12', '15', '18', '50', '22', '11'])
- ('Sorted list: ', ['50', '22', '18', '15', '12', '11'])
- ('The third in the list: ', '18')
复制代码
代碼
- import re, collections
- dict1 = collections.defaultdict(list)
- f = open("test.txt", "r")
- for line in f:
- p = re.match("(.+)\|.+\|.+\|(.+)", line)
- if p:
- dict1[p.groups()[0]].append(p.groups()[1])
- for i in dict1:
- print(i)
- print("Original list: ", dict1[i])
- print("Sorted list: ", sorted(dict1[i], key=lambda x:int(x), reverse=True))
- print("The third in the list: ", sorted(dict1[i], key=lambda x:int(x), reverse=True)[2])
复制代码
|
|