
- 使用set数据类型直接进行去重
当要去重的元素是dict或者[dict]就不是很理想
通过set去重字典
通过set去重[dict]
可以直接通过set去重列表、元组、字符串
a = (1, 2, 2, 1)
print("去重元组", set(a)) # 去重元组
#
a = [1, 2, 3, 2]
print("去重列表", set(a)) # 去重列表
#
a = '123123'
print("去重字符串", set(a)) # 去重字符串
- 通过字典的key去重
因为字典的key是不可以重复的,所以我们就可以通过字典的key来进行去重.
a = [1, 2, 3, 1, 2] dict1 = {} for i in a: dict1[i] = '' print("通过字典的可以来进行去重", dict1.keys()) - 通过python内置的函数来去重
我们可以使用reduce这个方法来进行去重
官方的一段介绍
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
加粗样式a = [1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7] def fun1(a, b): if not str(b) in a: a.append(str(b)) return a c = reduce(fun1, [[], ] + a) print(c)
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)