例如,给定列表['one', 'two', 'one'],算法应该返回True,而给定['one', 'two', 'three']则应该返回False。
当前回答
my_list = ['one', 'two', 'one']
duplicates = []
for value in my_list:
if my_list.count(value) > 1:
if value not in duplicates:
duplicates.append(value)
print(duplicates) //["one"]
其他回答
仅推荐用于短列表:
any(thelist.count(x) > 1 for x in thelist)
不要在一个很长的列表上使用——它所花费的时间与列表中项目数量的平方成正比!
对于具有可哈希项(字符串,数字和c)的较长列表:
def anydup(thelist):
seen = set()
for x in thelist:
if x in seen: return True
seen.add(x)
return False
如果你的项目是不可哈希的(子列表,字典等),它会变得更加复杂,尽管它仍然有可能得到O(N logN),如果它们至少具有可比性。但你需要知道或测试项目的特征(可哈希与否,可比性与否),以获得最佳性能——可哈希对象为O(N),不可哈希对象为O(N log N),否则就会变成O(N平方),没有人能做什么:-(。
如果所有值都是可哈希的,使用set()删除重复项:
>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True
一个更简单的解决方案如下。只需用pandas . replicated()方法检查True/False,然后取sum。请参阅pandas. series . replicated - pandas 0.24.1文档
import pandas as pd
def has_duplicated(l):
return pd.Series(l).duplicated().sum() > 0
print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False
如果您喜欢函数式编程风格,这里有一个有用的函数,使用doctest自文档和测试代码。
def decompose(a_list):
"""Turns a list into a set of all elements and a set of duplicated elements.
Returns a pair of sets. The first one contains elements
that are found at least once in the list. The second one
contains elements that appear more than once.
>>> decompose([1,2,3,5,3,2,6])
(set([1, 2, 3, 5, 6]), set([2, 3]))
"""
return reduce(
lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
a_list,
(set(), set()))
if __name__ == "__main__":
import doctest
doctest.testmod()
从这里你可以通过检查返回对的第二个元素是否为空来测试唯一性:
def is_set(l):
"""Test if there is no duplicate element in l.
>>> is_set([1,2,3])
True
>>> is_set([1,2,1])
False
>>> is_set([])
True
"""
return not decompose(l)[1]
注意,这并不有效,因为您是显式地构造分解。但是在使用reduce的过程中,你可以得到一些等价的(但效率稍低)答案5:
def is_set(l):
try:
def func(s, o):
if o in s:
raise Exception
return s.union([o])
reduce(func, l, set())
return True
except:
return False
这是老问题了,但这里的答案让我找到了一个略有不同的解决方案。如果您准备滥用推导式,您可能会以这种方式短路。
xs = [1, 2, 1]
s = set()
any(x in s or s.add(x) for x in xs)
# You can use a similar approach to actually retrieve the duplicates.
s = set()
duplicates = set(x for x in xs if x in s or s.add(x))
推荐文章
- Numpy Max vs amax vs maximum
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- 将整数转换为字符串,以逗号表示千
- Python日志记录不输出任何东西
- 将JavaScript字符串中的多个空格替换为单个空格
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?