name : major : start time : mark
Dean : English : 05:00:00 : 70
Dean : Japan : 06:00:00 : 80
Sam : France : 07:00.00 : 60
上面的示例在 sample.txt 中。我想按照以下說明獲得輸出。請你幫助我好嗎。
- 我想用 (:) 分割行并逐行閱讀
- 如果發現重名,則輸出開始時間較早的名稱。對于上面的 sample.txt, 將輸出Dean : English : 05:00:00 : 70 。
with open("sample.txt", mode="r") as f:
text = f.readlines()
for line in text:
line_data = line.split(":")
name = line_data[0].strip()
---------
---------
---------
uj5u.com熱心網友回復:
我已發表評論以供解釋:
from itertools import groupby
from time import strptime
from re import search
with open('s.txt') as f:
# skipping the header
header = next(f)
lines = [line.strip() for line in f]
# we need to sort the list first because we will use groupby later. This
# sorting is based on name (first item in every line after splitting)
lines.sort(key=lambda x: x.split(':', maxsplit=1)[0].strip())
# Now we are ready to group by again based on the previous condition I mean
# (first item in every line after splitting).
lists = [list(g) for _, g in
groupby(lines, key=lambda x: x.split(':', maxsplit=1)[0].strip())]
time_pattern = r'\d{2}:\d{2}:\d{2}'
# It's time to iterate over the list and print the items. Lists with more than
# one item need to be sorted because they had duplicate names. This sorting
# is based on the time. We will first get the time with regex then create an
# `time` object from it. `time` objects are sortable. After sorting,
# we just want the first item to be printed which has the smallest time.
for item in lists:
if len(item) > 1:
item.sort(
key=lambda x: strptime(search(time_pattern, x).group(), "%H:%M:%S"))
print(item[0])
else:
print(item[0])
輸出:
Dean : English : 05:00:00 : 70
Sam : France : 07:00.00 : 60
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/415591.html
標籤:
上一篇:pygame不更新x和y
下一篇:從單詞串列中查找字符出現百分比
