Python 从文本文件中显示温度较高的5个城市
我有一个包含一些城市和温度的文本文件,如下所示: 城市1 16 城市2 4 城市100 20 我用下面的代码显示温度较高的城市 但是我想展示5个温度较高的城市。你有办法做到这一点吗?我在这里做一些测试,但我总是在同一个城市显示5次Python 从文本文件中显示温度较高的5个城市,python,Python,我有一个包含一些城市和温度的文本文件,如下所示: 城市1 16 城市2 4 城市100 20 我用下面的代码显示温度较高的城市 但是我想展示5个温度较高的城市。你有办法做到这一点吗?我在这里做一些测试,但我总是在同一个城市显示5次 #!/usr/bin/env python import sys current_city = None current_max = 0 city = None for line in sys.stdin: line = line.strip()
#!/usr/bin/env python
import sys
current_city = None
current_max = 0
city = None
for line in sys.stdin:
line = line.strip()
city, temperature = line.rsplit('\t', 1)
try:
temperature = float(temperature)
except ValueError:
continue
if temperature > current_max:
current_max = temperature
current_city = city
print '%s\t%s' % (current_city, current_max)
将温度和城市列表存储在列表中。对列表进行排序。然后,取最后5种元素:它们将是您的五种最高温度。您可以使用:
我喜欢熊猫。这不是一个完整的答案,但我喜欢鼓励人们进行研究。看看这个
listA = [1,2,3,4,5,6,7,8,9]
import pandas as pd
df = pd.DataFrame(listA)
df.sort(0)
df.tail()
使用Pandas,您将希望了解系列和数据帧。DataFrames有很多功能,您可以命名列,直接从输入文件创建,几乎可以按任何方式排序。有常见的unix单词head和tail(begging和end),您可以指定返回的行数……等等。我喜欢《Python for Data Analysis》(Python for Data Analysis)一书。将数据读入一个列表,对列表进行排序,然后显示前5个:
cities = []
for line in sys.stdin:
line = line.strip()
city, temp = line.rsplit('\t', 1)
cities.append((city, int(temp))
cities.sort(key=lambda city, temp: -temp)
for city, temp in cities[:5]:
print city, temp
它将城市、温度对存储在一个列表中,然后对列表进行排序。
排序
中的键
功能告诉列表按温度下降进行排序,因此列表的前5个元素[:5]
是五个温度最高的城市。以下代码正好执行您需要的操作:
fname = "haha.txt"
with open(fname) as f:
content = f.readlines()
content = [line.split(' ') for line in content]
for line in content:
line[1] = float(line[1])
from operator import itemgetter
content = sorted(content, key=itemgetter(1))
print content
要获得最高温度的国家:
print content[-1]
要获得温度最高的5个国家:
print content[-6:-1]
它显示相同的城市,因为您的打印语句位于for循环之后。它需要在for循环套件中(即,以4的间隔缩进),这对于显然是在学习该语言的人来说,似乎有点过分了。。。
print content[-6:-1]