我想找到實作這一目標的最佳方法。(我已經可以手動完成,但我正在尋找直接執行此操作的圖書館)。
我想根據第一個索引對串列串列進行排序并洗掉第一個索引的雙打。
sections = [
[1, 4, 1],
[5, 3, 2], # Sort on the first element of sublist
[2, 2, 3],
[2, 1, 4], # Double to remove
]
assertion = [
[1, 4, 1],
[2, 2, 3],
[5, 3, 2],
]
def sort_first_and_remove_double(sections):
return result
assert sort_first_and_remove_double(sections) == assertion
目標是不直接編碼任何回圈,而是使用庫在一行或兩行中進行編碼,出于優化原因,我的資料非常龐大。
我的嘗試代碼在這里:
def sort_first_and_remove_double(sections):
sections = remove_double(sections)
sections = sort_sections(sections)
return sections
def sort_sections(sections):
ids = get_ids(sections)
return [x for _, x in sorted(zip(ids, sections))]
def remove_double(sections):
ids = get_ids(sections)
keeped_sections = []
for i, id_check in enumerate(ids):
ids_keeped = get_ids(keeped_sections)
if id_check not in ids_keeped:
keeped_sections.append(sections[i])
return keeped_sections
def get_ids(sections):
return [section[0] for section in sections]
但是速度很慢!
編輯:這里更新時間:
t0 = time.perf_counter()
sort_first_and_remove_double(lst)
print(time.perf_counter() - t0) # 7.719699351582676e-05 s
t0 = time.perf_counter()
list(dict(map(lambda x: [x[1][0], x[1]], sorted(enumerate(lst), key=lambda pair: (pair[1][0], -pair[0])))).values())
print(time.perf_counter() - t0) # 7.587004802189767e-06 s
t0 = time.perf_counter()
sorted(dict(map(lambda x: (x[0], x), lst[::-1])).values())
print(time.perf_counter() - t0) # 3.0700030038133264e-06 s
uj5u.com熱心網友回復:
你不會這樣解決嗎?
sorted({x[0]: x for x in sections[::-1]}.values())
或不為
sorted(dict(map(lambda x: (x[0], x), sections[::-1])).values())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365973.html
