文章詳情頁(yè)
python - 如何去除重復(fù)的元素?
瀏覽:132日期:2022-06-27 14:23:26
問(wèn)題描述
例如上面第一行含有3:19和3:6,怎么寫代碼,讓最后的文件只取碰到的第一個(gè)?該例中則選擇3:19
問(wèn)題解答
回答1:因?yàn)椴恢滥隳谴亲址€是什么, 所以我這里先按照字符串的方式去實(shí)現(xiàn)
l = ’0:13 1:9 2:14 3:19 4:12 3:19’d = {}result = []for _ in l.split(): key = _.split(’:’)[0] if key not in d:d[key] = _result.append(d[key])print(result)print(result)# 輸出[’0:13’, ’1:9’, ’2:14’, ’3:19’, ’4:12’]回答2:
from itertools import groupbystr = ’0:13 1:9 2:14 3:19 4:12 3:6’lst = str.split()lst.sort()g_lst = [list(g)[0] for k, g in groupby(lst, key=lambda x: x.split(’:’)[0])]print g_lst#[’0:13’, ’1:9’, ’2:14’, ’3:19’, ’4:12’]
相關(guān)文章:
1. 數(shù)據(jù)庫(kù) - MySQL 單表500W+數(shù)據(jù),查詢超時(shí),如何優(yōu)化呢?2. javascript - 百度echarts series數(shù)據(jù)更新問(wèn)題3. 求大神幫我看看是哪里寫錯(cuò)了 感謝細(xì)心解答4. MySQL客戶端吃掉了SQL注解?5. mac 安裝 python_MySQLdb6. javascript - 圖片能在網(wǎng)站顯示,但控制臺(tái)仍舊報(bào)錯(cuò)403 (Forbidden)7. php自學(xué)從哪里開始?8. mysql - AttributeError: ’module’ object has no attribute ’MatchType’9. python小白的基礎(chǔ)問(wèn)題 關(guān)于while循環(huán)的嵌套10. phpstady在win10上運(yùn)行
排行榜

熱門標(biāo)簽