1.列表转字符串 如果列表中每个元素是字符串的话, ‘’.join(list0)
如果有是非字符串类型的元素, list1=[str(i) for i in list0] s=’’.join(list) #’‘表示以什么来拼接列表元素成为字符串,如以空格’ ’
2.字符串转列表 list1=list(s) 按特点分割列表 list1 = s.split( ’ ')#按空格
3.list.append() 这个函数是有记忆的,每次拼接都是会被其认为不同的元素。如 : l=[] l.append(‘a’) l.append(‘b’) a=’[]’.join(l) print(a)
输出:a[]b
list内置方法
- append(self, object)
用途:在list的末尾添加一个object。
返回值:返回一个添加object的list。
其中,object表示被添加目标(可以是任意类型)。
例`>>> test = ['python']
test.append(3) test ['python', 3] #输出结果
test.append([1, 2]) #添加一个列表 test ['python', 3, [1, 2]] #输出结果
test.append((5, 4,)) #添加一个元组 test ['python', 3, [1, 2], (4, 5)] #输出结果
test.append(2.7) #添加一个小数 test ['python', 3, [1, 2], (4, 5), 2.7]
`
- clear(self)
用途:将list清空。
返回值:返回一个空的list。
例`>>> test = ["python"]
test [] #输出结果,一个空的列表`
- copy(self)
用途:复制一份列表。
返回值:返回列表的一个副本(修改副本不会改变原有的列表)。
例`>>> test = ["python"]
testCopy = test.copy() testCopy ["python"] #输出结果
testCopy.append(3) testCopy ["python", 3] #输出结果
test ["python"] #输出结果,改变其副本,并不会改变原有列表`
- count(self, object)
用途:在list中统计object的个数。
返回值:返回object的个数。
其中,object表示被统计的元素(可以是任意类型)。
例`>>> test = ["python"]
test.count("python") 1 #输出结果
test.append("python") test.count("python") 2 #输出结果`
- extend(self, iterable)
用途:在list的末尾添加元素。(注:区分append和extend的区别)
返回值:返回在列表中添加元素后的list。
其中,iterable表示能够迭代的元素(数字不能迭代)。
例`>>> test = ["python"]
test.extend([1, 2, 3]) test ['python', 1, 2, 3] #输出结果
test = ["python"] test.append([1, 2, 3]) #区分extend和append test ['python', [1, 2, 3]] #输出结果
test = ["python"] test.extend("extend") test ['python', 'e', 'x', 't', 'e', 'n', 'd'] #输出结果,如果是字符串,则会一个字符一个字符的迭代添加
test.extend((1,2,3,)) #添加一个元组 test ['python', 'e', 'x', 't', 'e', 'n', 'd', 1, 2, 3] #输出结果
test.extend(666) #数字不能迭代 Traceback (most recent call last): File "<pyshell#40>", line 1, in test.extend(666) TypeError: 'int' object is not iterable`