#python
#python
Вопрос:
Основываясь на текстовой информации, мне необходимо найти для каждого дня самый низкий и самый высокий прилив в метрах и распечатать их на экране для каждого дня.
Thursday 4 January,11.58,0.38 meters
Thursday 4 January,16.95,0.73 meters
Thursday 4 January,23.68,0.02 meters
Friday 5 January,6.48,0.83 meters
Friday 5 January,12.42,0.33 meters
Friday 5 January,17.92,0.75 meters
Saturday 6 January,0.5,0.02 meters
Saturday 6 January,7.18,0.85 meters
Saturday 6 January,13.2,0.29 meters
Saturday 6 January,18.82,0.75 meters
желаемый результат будет примерно таким:
Thursday 4 January: 0.02 meters at lowest and 0.73 meters at highest
friday 5 January: 0.33 meters at lowest and 0.83 meters at highest
Мне удалось вызвать текстовый файл и распечатать его в нужном формате, но я понятия не имею, как отсортировать его в этом формате.
aFile = open('C:\Users\User\PycharmProjects\Tides.txt')
for line in aFile:
line = line.strip()
line = line.replace('meters', '')
print(f": {[line]}")
Пожалуйста, помогите, новичок в Python здесь
Комментарии:
1. Используйте
line.split(',')
и посмотрите, что произойдет сline
.
Ответ №1:
С помощью модуля csv
и collections
.
Пример:
import csv
from collections import defaultdict
result = defaultdict(list)
with open(filename) as infile:
reader = csv.reader(infile)
for line in reader:
result[line[0]].append(float(line[2].strip("meters")))
for k, v in result.items():
print("{}: {} meters at lowest and {} meters at highest".format(k, min(v), max(v)))
Вывод:
Saturday 6 January: 0.02 meters at lowest and 0.85 meters at highest
Friday 5 January: 0.33 meters at lowest and 0.83 meters at highest
Thursday 4 January: 0.02 meters at lowest and 0.73 meters at highest
Ответ №2:
Попробуй это :
aFile = open('tides.txt')
d = {}
for line in aFile:
line = line.strip()
line = line.replace('meters', '')
# After this split the line wrt ,
line = line.split(',')
# Assign the day as key and the the tide height as value inside value list
if line[0] in d:
d[line[0]].append(line[-1])
else:
d[line[0]] = [line[-1]]
for k in d:
print(k, ":", min(d[k]), " meters at lowest and ", max(d[k]), " meters at highest")
ВЫВОД :
Thursday 4 January : 0.02 meters at lowest and 0.73 meters at highest
Friday 5 January : 0.33 meters at lowest and 0.83 meters at highest
Saturday 6 January : 0.02 meters at lowest and 0.85 meters at highest