Python 列表去重怎么用暴力枚举法实现
希望各位大佬能提供代码,需求是时间复杂度最小
Python 列表去重怎么用暴力枚举法实现
set(x)
暴力枚举法实现列表去重,核心就是逐个检查每个元素,只保留第一次出现的那个。
def remove_duplicates_brute_force(lst):
"""
使用暴力枚举法去除列表中的重复元素,保持原有顺序。
"""
result = []
for i in range(len(lst)):
# 标记当前元素是否已经存在于结果列表中
is_duplicate = False
# 检查当前元素是否在之前的结果中已经出现过
for j in range(i):
if lst[i] == lst[j]:
is_duplicate = True
break
# 如果不是重复的,就添加到结果列表
if not is_duplicate:
result.append(lst[i])
return result
# 测试一下
my_list = [1, 2, 2, 3, 4, 4, 5, 1, 6]
unique_list = remove_duplicates_brute_force(my_list)
print(f"原始列表: {my_list}")
print(f"去重后列表: {unique_list}")
这个方法的思路很简单:外层循环遍历每个元素,内层循环检查当前元素是否在之前的位置出现过。如果没出现过,就加到结果列表里。时间复杂度是O(n²),对于大数据量效率不高,但作为理解算法原理的练习还不错。
实际开发中直接用list(set(original_list))或者用字典保持顺序更高效。
一楼正解,此贴终结
如果要求保持顺序,list({i:None for i in x}.keys())
忘记说了,python3
python3.5 也是无序的,3.6 是有序的,但是不要依赖这一实现
3.6 以上 保证顺序
3.6 以上的 cpython 保证顺序
请问你们是指 3.6 的 set()有序还算 list(set())有序?
set 就够了
指的是 Dict
这里不能保持有序吧,生成 dict 时失序了,再调用 keys 仍然无序
3.6 的 dict 变成有序的吗
楼主是否看过 python cookbook ?
If the values in the sequence are hashable, the problem can be easily solved using a set and a generator. For example:
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item seen.add(item)
Here is an example of how to use your function:
>>> a = [1, 5, 2, 1, 9, 1, 5, 10]
>>> list(dedupe(a))
[1, 5, 2, 9, 10]
>>>
This only works if the items in the sequence are hashable. If you are trying to eliminate duplicates in a sequence of unhashable types (such as dicts), you can make a slight change to this recipe, as follows:
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
Here, the purpose of the key argument is to specify a function that converts sequence items into a hashable type for the purposes of duplicate detection. Here ’ s how it works:
>>> a = [ {‘x’:1, ‘y’:2}, {‘x’:1, ‘y’:3}, {‘x’:1, ‘y’:2}, {‘x’:2, ‘y’:4}]
>>> list(dedupe(a, key=lambda d: (d[‘x’],d[‘y’])))
[{‘x’: 1, ‘y’: 2}, {‘x’: 1, ‘y’: 3}, {‘x’: 2, ‘y’: 4}]
>>> list(dedupe(a, key=lambda d: d[‘x’]))
[{‘x’: 1, ‘y’: 2}, {‘x’: 2, ‘y’: 4}]
>>>
This latter solution also works nicely if you want to eliminate duplicates based on the value of a single field or attribute or a larger data structure.
res = []
lists = = [res.append(i) for i in target if i not in res]
我忘了在哪看过的一个以前没见过的操作,去重保留顺序
ccc = [1, 3, 5, 8, 9, 3, 5, 9, 10]
res = sorted(set(ccc), key=ccc.index)
print res
=>[1, 3, 5, 8, 9, 10]


