在Python的编程中,我们希望简约含有重复列表的列表,即对含有重复列表的列表求其集合,这个需求还是比较常见的。例如:
L = [['Banana'],['Orange'],['Orange'],['Orange'],[],[],[],['Mango','Strawberry'],['Apple'],['Mango', 'Strawberry'], ['Mango','Strawberry']]
我们想求这类列表的集合,如果直接用set命令,会得到TypeError的错误。
>>> L
[['Banana'], ['Orange'], ['Orange'], ['Orange'], [], [], [], ['Mango', 'Strawberry'], ['Apple'], ['Mango', 'Strawberry'], ['Mango', 'Strawberry']]
>>> set(L)
Traceback (most recent call last):
File "<pyshell#86>", line 1, in <module>
set(L)
TypeError: unhashable type: 'list'
为了删除重复的列表,每个列表仅保留一个,我编写如下的程序:
# Author:Li Xing Mar 2nd,2018
# Simplied the multi-lists
def list_simplied(org_lst):
lst_len = len(org_lst)
if lst_len == 0 or lst_len == 1:
return org_lst
else:
simplied_lst = []
repeated_index =[]
for i in range(lst_len):
if i in repeated_index:
continue
else:
temp = org_lst[i]
for j in range(i+1,lst_len):
if org_lst[j] == temp:
repeated_index.append(j)
simplied_lst.append(temp)
return simplied_lst
>>> list_simplied(L)
[['Banana'], ['Orange'], [], ['Mango', 'Strawberry'], ['Apple']]
list_simplied函数的对象item,可以是元素、列表、字典等等,例如:
>>> lst = [1,1,3,4,5,6,6,6,7]
>>> list_simplied(lst)
[1, 3, 4, 5, 6, 7]
>>> x = [{1:'a',2:'b',3:'c'},{1:'a',2:'b',3:'c'},{},{}]
>>> list_simplied(x)
[{1: 'a', 2: 'b', 3: 'c'}, {}]
喜欢的话,点个赞吧!