woxio770 发表于 2017-4-29 10:52:05

python list里去重复的元素

1.通过set 函数进行实现,非常简单。
  点击(此处)折叠或打开


[*]#!/usr/bin/python

[*]list_string = ['123','abc','abc','cde']
[*]list_string = list(set(list_string))
[*]print list_string


输出的list就是去掉重复的结果

2.



[*]#!/usr/bin/python

[*]# Filename: DeleteRep
[*]# use: to delete the repetation of the string
[*]
[*]StringList=['123','abc','abc','cde','cde']
[*]index = 1
[*]compare = 0
[*]length = len(StringList) - 1
[*]while index <= length:
[*]    if cmp(StringList[index],StringList[compare]) == 0:
[*]        del StringList[index]
[*]        length -= 1                        #每次del之后List长度都减少
[*]        if index == length + 1:         #限制最后出现末尾两个是重复的现象的终止
[*]            break
[*]    else:
[*]         index += 1
[*] compare += 1
[*] print StringList



 
页: [1]
查看完整版本: python list里去重复的元素