我如何检查一个列表是否有任何重复,并返回一个没有重复的新列表?
当前回答
如果你想删除重复项(就地编辑而不是返回新列表)而不使用内置set, dict,请检查此选项。键,唯一,计数器
>>> t = [1, 2, 3, 1, 2, 5, 6, 7, 8]
>>> for i in t:
... if i in t[t.index(i)+1:]:
... t.remove(i)
...
>>> t
[3, 1, 2, 5, 6, 7, 8]
其他回答
它需要安装一个第三方模块,但包iteration_utilities包含一个unique_everseen1函数,可以删除所有重复的同时保留顺序:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen(['a', 'b', 'c', 'd'] + ['a', 'c', 'd']))
['a', 'b', 'c', 'd']
如果你想避免列表添加操作的开销,你可以使用itertools。链:
>>> from itertools import chain
>>> list(unique_everseen(chain(['a', 'b', 'c', 'd'], ['a', 'c', 'd'])))
['a', 'b', 'c', 'd']
unique_everseen也适用于列表中有不可哈希项(例如列表)的情况:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen([['a'], ['b'], 'c', 'd'] + ['a', 'c', 'd']))
[['a'], ['b'], 'c', 'd', 'a']
然而,这将比项目是可哈希的(多)慢。
1披露:我是iteration_utilities-library的作者。
要删除重复的,将其设置为SET,然后再次将其设置为LIST,并打印/使用它。 一个集合保证有唯一的元素。例如:
a = [1,2,3,4,5,9,11,15]
b = [4,5,6,7,8]
c=a+b
print c
print list(set(c)) #one line for getting unique elements of c
输出将如下所示(在python 2.7中检查)
[1, 2, 3, 4, 5, 9, 11, 15, 4, 5, 6, 7, 8] #simple list addition with duplicates
[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15] #duplicates removed!!
Write a Python program to create a list of numbers by taking input from the user and then remove the duplicates from the list. You can take input of non-zero numbers, with an appropriate prompt, from the user until the user enters a zero to create the list assuming that the numbers are non-zero.
Sample Input: [10, 34, 18, 10, 12, 34, 18, 20, 25, 20]
Output: [10, 34, 18, 12, 20, 25]
lst = []
print("ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!!")
print("ENTER LIST ELEMENTS :: ")
while True:
n = int(input())
if n == 0 :
print("!!!!!!!!!!! EXIT !!!!!!!!!!!!")
break
else :
lst.append(n)
print("LIST ELEMENR ARE :: ",lst)
#dup = set()
uniq = []
for x in lst:
if x not in uniq:
uniq.append(x)
# dup.add(x)
print("UNIQUE ELEMENTS IN LIST ARE :: ",uniq)
这只是一个可读的函数,很容易理解,我已经使用了dict数据结构,我已经使用了一些内置函数和更好的复杂度O(n)
def undup(dup_list):
b={}
for i in dup_list:
b.update({i:1})
return b.keys()
a=["a",'b','a']
print undup(a)
免责声明:你可能会得到缩进错误(如果复制和粘贴),使用上述代码与适当的缩进粘贴之前
你可以使用set来删除重复项:
mylist = list(set(mylist))
但请注意,结果将是无序的。如果这是个问题的话:
mylist.sort()
推荐文章
- Visual Studio Code:如何调试Python脚本的参数
- 如何克隆或复制一个列表在kotlin
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 非递归深度优先搜索算法
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 如何在c#中连接列表?