本文介紹了在 Python 的列表中保留重復項的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我知道這可能是一個簡單的答案,但我想不通.Python中將重復項保存在列表中的最佳方法是什么:
I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list:
x = [1,2,2,2,3,4,5,6,6,7]
輸出應該是:
[2,6]
我找到了這個鏈接:查找(并保留)子列表的重復項在 python 中,但我對 Python 還是比較陌生,我不能讓它為一個簡單的列表工作.
I found this link: Find (and keep) duplicates of sublist in python, but I'm still relatively new to Python and I can't get it to work for a simple list.
推薦答案
如果列表已經排序,這是一個簡單的方法:
This is a short way to do it if the list is sorted already:
x = [1,2,2,2,3,4,5,6,6,7]
from itertools import groupby
print [key for key,group in groupby(x) if len(list(group)) > 1]
這篇關于在 Python 的列表中保留重復項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!