在Python中,找出列表中相同的元素可以通过以下几种方法:
1. 使用集合(set):
def find_duplicates(lst):return set([x for x in lst if lst.count(x) > 1])
2. 使用字典(dict)记录元素出现次数:
def find_duplicates(lst):d = {}for i in lst:if i in d:d[i] += 1else:d[i] = 1return [k for k, v in d.items() if v > 1]
3. 使用列表推导式:

def find_duplicates(lst):return [x for x in lst if lst.count(x) > 1]
4. 使用`Counter`类从`collections`模块:
from collections import Counterdef find_duplicates(lst):count = Counter(lst)return [key for key, value in count.items() if value > 1]
5. 使用`numpy`库的`where`和`argwhere`方法:
import numpy as npdef find_duplicates(lst):a = np.array(lst)eq_letter = np.where(a == a)return eq_letter
以上方法都可以找出列表中的重复元素。选择哪一种方法取决于你的具体需求和列表的大小。需要注意的是,使用集合方法去重后,你将无法知道哪些元素是重复的。如果你需要知道每个元素重复的次数,可以使用`Counter`类
