我目前有兩個串列和一個作業腳本,當給定來自 的元素時,會找到30 分鐘內的list_a所有日期時間。社區在上一個問題list_b中幫助了我。
我用一個元組串列替換了其中一個串列,并一直試圖在腳本中協調它——我將在下面解釋我試圖做出的一些修改。
# Old Set of Two Lists
list_a = ["10:26:42", "8:55:43", "7:34:11"]
list_b = ["10:49:20", "8:51:10", "10:34:35", "8:39:47", "7:11:49", "7:42:10"]
# Previous Output
10:26:42 is within 30m of 10:49:20, 10:34:35
08:55:43 is within 30m of 08:51:10, 08:39:47
07:34:11 is within 30m of 07:11:49, 07:42:10
# Old List and New List of Tuples
my_flights = ["10:26:42", "8:55:43", "7:34:11"]
alt_flights = [("10:49:20", "Frontier"), ("8:51:10", "Southwest"), ("10:34:35", "Jet Blue"), ("8:39:47", "Delta"), ("7:11:49", "Spirit"), ("7:42:10", "American"]
# Desired Output
10:26:42 is within 30m of Frontier, Jet Blue at 10:49:20, 10:34:35
10:26:42 is within 30m of Southwest, Delta at 08:51:10, 08:39:47
10:26:42 is within 30m of Spirit, American at 07:11:49, 07:42:10
舊的兩個串列的作業腳本如下,我要做的是(1)替換list_a為my_flights(2)替換list_b為alt_flights和(3)在alt_flights我的輸出中使用名稱!
def str2time(s):
h,m,s = map(int, s.split(':'))
return datetime.timedelta(hours=h, minutes=m, seconds
z = datetime.datetime(1900,1,1)
for a in map(str2time, list_a):
start = f'{z a:%H:%M:%S} is within 30m of'
for b in map(str2time, list_b):
if abs(a-b).total_seconds() <= 1800:
print(f'{start} {z b:%H:%M:%S}', end='')
start = ','
if start == ',':
print()
嘗試修改:我想我可以稍后更改list_b并for b in map(str2time, alt_flights[0][0])參考alt_flights[0][1]以提取航空公司名稱,但這會引發錯誤str2time()。然后我想我可以在下面做一個檢查if abs(a-b).total_seconds() <= 1800:,檢查if b in alt_flights哪個會獲取當前航空公司名稱的值list_b[0][1]。但是,這兩個都失敗了。
uj5u.com熱心網友回復:
如果您在列印期間將時間資料傳遞給,而不是在回圈之前映射時間alt_flights,可能會更容易閱讀。str2time如果你更換
for b in map(str2time, list_b):
if abs(a-b).total_seconds() <= 1800:
print(f'{start} {z b:%H:%M:%S}', end='')
和
for time, airline in alt_flights:
if abs(a - str2time(time)).total_seconds() <= 1800:
print(f"{start} {str2time(time)} {airline}", end='')
代碼將按預期作業。
完整的第二次迭代:
for a in map(str2time, my_flights):
start = f'{z a:%H:%M:%S} is within 30m of'
for time, airline in alt_flights:
if abs(a - str2time(time)).total_seconds() <= 1800:
print(f"{start} {str2time(time)} {airline}", end='')
start = ','
if start == ',':
print()
輸出:
10:26:42 is within 30m of 10:49:20 Frontier, 10:34:35 Jet Blue
08:55:43 is within 30m of 8:51:10 Southwest, 8:39:47 Delta
07:34:11 is within 30m of 7:11:49 Spirit, 7:42:10 American
uj5u.com熱心網友回復:
您需要使用的任何特殊原因map?
for b_time, b_name in alt_flights:
if abs(a-str2time(b_time)).total_seconds() <= 1800:
print(f"{start} {z b:%H:%M:%S} {b_name}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410906.html
標籤:
