亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按兩位數排序行

按兩位數排序行

眼眸繁星 2023-02-15 15:28:14
您好,我有一個如下所示的文本文件:file '4. Can This Be Love.mp3' file '3. I Wanna Share It With You.mp3' file '8. Hold On.mp3' file '6. Playing With Fire.mp3' file '1. Take Me To The River.mp3' file '5. Giving It Up For You.mp3' file '10. Hooked On You.mp3' file '9. I Can'\''t Stop.mp3' file '7. Make It Together.mp3' file '2. Can'\''t Stop Myself.mp3' 我正在嘗試按開頭的字符串編號對文件進行排序,以便按從 1 到 10 的正確順序排列。我的代碼如下所示:#open file to readshopping = open(songInputsFilepath, "r")#get lines from filelines = shopping.readlines()#sort lineslines.sort()#close fileshopping.close()#open file for writingshoppingwrite = open(songInputsFilepath, "w")#write sorted lines to fileshoppingwrite.writelines(lines)#close file for writingshoppingwrite.close() 它幾乎可以工作,但放錯了第 10 首曲目,并導致文件排序如下:file '1. Take Me To The River.mp3' file '10. Hooked On You.mp3' file '2. Can'\''t Stop Myself.mp3' file '3. I Wanna Share It With You.mp3' file '4. Can This Be Love.mp3' file '5. Giving It Up For You.mp3' file '6. Playing With Fire.mp3' file '7. Make It Together.mp3' file '8. Hold On.mp3' file '9. I Can'\''t Stop.mp3' 有什么方法可以告訴 lines.sort() 函數使用正則表達式僅根據第一個“句點”字符之前的字符串對每一行進行排序?
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

如果您不介意使用正則表達式,這會起作用:

添加import re在文件的頂部。

改變這個:

lines.sort()

對此:

lines.sort(key=lambda x: int(re.findall('\d+', x)[0]))

或者使用搜索(應該更快),正如@wjandrea 所建議的:

lines.sort(key=lambda x: int(re.search('\d+', x).group()))

您也可以通過將鍵設置為切掉第一個數字字符來完成同樣的事情,盡管它可能會稍微冗長一些。


查看完整回答
反對 回復 2023-02-15
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號