Posted in Python onJuly 20, 2019
如下所示:
# x = ['c b a',"e d f"] # y = [] # for i in x: # for ii in i: # # print(ii) # if ii == ' ': # pass # else: # y.append(ii) # print(y)
# python 清除列表中的空字符
# list1 = ['122','2333','3444',' ','422',' ',' ','54',' '] # 第一种方法会导致最后一个' '没有被移除掉['122', '2333', '3444', '422', '54', ' '] # for x in list1: # if x == ' ': # list1.remove(' ') # print(list1) # 第二种方法:['122', '2333', '3444', '422', '54'] # for x in list1: # if ' ' in list1: # list1.remove(' ') # print(list1) # 第三种方法:遍历空格的个数,然后逐个删除 # for x in range(list1.count(' ')): # list1.remove(' ') # print(list1) # 第四种方法:用了while和for一样 # while ' ' in list1: # list1.remove(' ') # print(list1)
# 去除字符串中间的空格
# 第一种方法:使用replace,但是这种方法很笨,如果字符串中间有一万个空格怎么办,也要全部打出来吗 # a = 'hello world' # b = a.replace(' ','') # print(b) # 第二种方法: # a = 'hello world' # a = list(a) # for x in a: # if ' ' in a: # a.remove(' ') # bb = ''.join(a) # print(bb) # a = 'hello wor ld' # # aa = a.split() # # print(aa) # # print(''.join(aa)) # print(''.join(a.split())) # list1 = ['122','2333','3444',' ','422',' ',' ','54',' '] # for x in list1: # for i,j in enumerate(list1): # print(i,j) # if x == ' ': # list1.remove(' ') # print(list1) # print('***************************************') # print(list1)
# 去除列表中的重复元素
# 方法一: 对列表进行怕羞,从头到尾进行比较,遇到重复的元素就删除,否则指针向右移动一位 #方法1,逻辑复杂,临时变量保存值消耗内存,返回结果破坏了原列表顺序,效率最差 # def deleteDuplicatedElement(l): # l.sort() # length = len(l) # firstItem = l[0] # for x in range(1,length-1): # # if x < length - 2: # # if l[x] == l[x+1]: # # l.remove(l[x]) # # return l # currentItem = l[x] # if firstItem == currentItem: # l.remove(currentItem) # else: # firstItem = currentItem # return l # print(deleteDuplicatedElement(['d','d','1','2','1','4'])) # def deleteDuplicatedElement(l): # l.sort() # length = len(l) # lastItem = l[length-1] # for x in range(length-2,-1,-1): # currentItem = l[x] # if lastItem == currentItem: # l.remove(currentItem) # else: # lastItem = currentItem # return l # print(deleteDuplicatedElement(['python','r','r','g','g','g','t','y','g','n'])) # 方法二:设一临时列表保存结果,从头遍历原列表,如临时列表中没有当前元素则追加: #方法2,直接调用append方法原处修改列表,逻辑清晰,效率次之 # def deleteDuplicatedElement(l): # ll = [] # for x in l: # if x in ll: # continue # else: # ll.append(x) # return ll # print(deleteDuplicatedElement(['python','r','r','g','g','g','t','y','g','n'])) # 方法三:利用Python中集合元素唯一性特点,将列表转换为集合,然后转换为列表输出即可 #方法3,极度简洁,使用python原生方法效率最高,但列表原有顺序被打乱 # def deleteDuplicatedElement(l): # return sorted(list(set(l)),key=l.index) # print(deleteDuplicatedElement(['python','r','r','g','g','g','t','y','g','n']))
以上这篇Python 列表去重去除空字符的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。
Python 列表去重去除空字符的例子
- Author -
Fortune_yang声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@