ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]
ids = list(set(ids))
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]
new_ids = []
for item in ids:
if item not in new_ids:
new_ids.append(item)
ids = [1, 3, 8, 3, 8, 1, 9, 9, 9, 1]
func = lambda x, y: x if y in x else x + [y]
ids = reduce(func, [[], ] + ids)
class A:
def __init__(self, no, name):
self.no = no
self.name = name
def __eq__(self, other):
return self.no == other.no and self.name == other.name
def __hash__(self):
return hash(self.no) ^ hash(self.name)
def __repr__(self):
return str(self.no)+":"+self.name
a_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]
a_list = list(set(a_list))
# a_list = [1:b, 2:a, 1:a]
a_list.sort(key=lambda a: a.no) # 按no排序
a_list.sort(key=lambda a: a.name) # 按name排序
必须实现”__eq__”和”__hash__”方法。
“__eq__”用于判断是否相等,”__hash__”用于计算hash值。
因为set存取的必须是不可变类型,它是依赖”__hash__”来计算桶的位置,而利用”__eq__”来判断元素之间是否相等。
关于其更多的介绍:https://segmentfault.com/a/1190000003969462
class A:
def __init__(self, no, name):
self.no = no
self.name = name
def __eq__(self, other):
return self.no == other.no and self.name == other.name
def __repr__(self):
return str(self.no)+":"+self.name
a_list = [A(1, "a"), A(2, "a"), A(1, "a"), A(1, "b")]
new_a_list = []
for a in a_list:
if a not in new_a_list:
new_a_list.append(a)
注意这里实现了”__eq__”方法,才能使得“if a not in new_a_list:”语句生效。
class A:
def __init__(self, no, name):
self.no = no
self.name = name
def __repr__(self):
return str(self.no)+":"+self.name
# no为"主键"
a_list = [A(1, "a"), A(2, "b"), A(1, "a"), A(3, "b")]
mp = {}
for a in a_list:
if a.no not in mp:
mp[a.no] = 1
else:
mp[a.no] += 1
a_list.remove(a)