本文共 1183 字,大约阅读时间需要 3 分钟。
# -*- coding: utf-8# @Time : 2020/12/8 10:38# @Author : ZYX# @File : lambda01.py# @software: PyCharmimport pandas as pddata = open('data/countries_zh.txt', 'r',encoding='utf-8')countries = []for line in data: line = line.strip() # 去除空格 arr = line.split("\t") # 按照制表符分割 name = arr[1] # 取出国家名 caption = arr[3] # 取出首都名 population = int(arr[4]) # 取出人口数 countries.append([name, caption, population]) # 追加到countries数组中# 遍历countriesfor each_country in countries: print(each_country)print('*'*100)
通过观察数据集可以看出,主要是以制表符\t
来进行排版的,并且第一列是url
,第二列是国家
。第三列是大洲
,第四列是首都
,第五列是人口数量信息
。首先通过简单的数据提取提出所需要的国家首都和人口信息。
遍历结果集:
方法一:自定义函数
#排序 --- 按照人口数# 定义方法获取每个国家的人口数def get_population(country): return country[2]# 排序countries.sort(key=get_population)for each_country in countries: print(each_country)print('*'*100)
通过自定义的函数获取到每组的人口数量信息,索引为2,再将其作为排序参数传入sort方法对原始数据进行排序。
方法二:Lambda表达式
# 使用lambda表达式# get_population = lambda country:country[2]countries.sort(key=lambda country:country[2])for each_country in countries: print(each_country)
直接将上述的方法压缩为一行lambda表达式作为参数传入sort方法。
转载地址:http://bweq.baihongyu.com/