1、使用Python实现列表[1,3,5,5,3,7,9]去重
思路:将列表转换成集合,就可以实现去重的功能。
mylist = [1,3,5,5,3,7,9]
myset = set(mylist)
newlist = [i for i in myset]
2、将[[11,12],[21,22],[31,32]]展开,得到列表[11, 12, 21, 22, 31, 32]
思路:可以通过两种方式实现:(1)使用for循环遍历;(2)使用numpy中的flatten函数。
#方法一
list1 = [[11,12],[21,22],[31,32]]
newlist1 = [j for i in list1 for j in i]
#方法二
import numpy as np
newlist2 = np.array(list1).flatten().tolist()
3、去除字符串’Hello Worle Python’中的空格
思路:可以通过两种方式实现:(1)replace函数;(2)先使用split函数切割,再用join函数组合。
#方法一
mystr = 'Hello World Python'
newres1 = mystr.replace(' ','')
#方法二
mystrlist = mystr.split(' ')
newres2 = ''.join(mystrlist)