1.函數(shù)list (實際上是一個類)
# 將其他類型轉(zhuǎn)換成列表
temp = list('hello')
print(temp)
# 將列表轉(zhuǎn)換成字符串
temp = ''.join(temp)
print(temp)
========================1=========================
['h', 'e', 'l', 'l', 'o']
hello
2.列表的基本操作
# 修改元素的值
x = [1, 1, 1]
x[1] = 2
print(x)
# 刪除元素
temp = ['python', 'c', 'java']
del temp[1]
print(temp)
# 切片賦值
temp = list('perl')
temp[2:] = 'ar'
print(temp)
# 可以賦不同的值
temp[2:] = 'arararararar'
print(temp)
# 插入新元素
temp = [1,2,3]
temp[1:1] = [4,4,4,4,4]
print(temp)
# 去除元素
temp[1:6] = []
print(temp)
========================2=========================
[1, 2, 1]
['python', 'java']
['p', 'e', 'a', 'r']
['p', 'e', 'a', 'r', 'a', 'r', 'a', 'r', 'a', 'r', 'a', 'r', 'a', 'r']
[1, 4, 4, 4, 4, 4, 2, 3]
[1, 2, 3]
3.列表方法
# 將一個對象插入到列表末尾
lst = [1,2,3]
lst.append(4)
print(lst)
# 清空列表
lst.clear()
print(lst)
# 復制列表
lst.copy()
# 常規(guī)復制( 只是指向同一個列表 )
a = [1,2,3]
b = a
b[1] = 4
print(a)
# 復制列表
b = a.copy()
b[1] = 2
print(a)
print(b)
# 查看對象在列表中出現(xiàn)的次數(shù)
a = [1,2,3,3,4]
print(a.count(3))
# 列表拓展列表(常規(guī)拼接返回的一個全新的列表)
a = [1,2,3]
a.extend([4,5,6])
print(a)
# 查找第一次出現(xiàn)的索引值
a = ['we', 'are', 'the', 'knights', 'who', 'say', 'ni']
print(a.index('are'))
# 將對象插入列表
numbers = [1,2,4]
numbers.insert(2, 'three')
print(numbers)
# 最后一個元素刪除
x = [1,2,3].pop()
print(x)
# 刪除第一個指定元素值
x = [1,'2',3,4]
x.remove('2')
print(x)
# 倒序
x.reverse()
print(x)
# 排序
x.sort()
print(x)
# 高級排序 sort(key) key: 為一個函數(shù), 使用函數(shù)創(chuàng)造出來的鍵, 再對鍵進行排序
x = ['abc', 'abac', 'a']
x.sort(key=len)
print(x)
========================3=========================
[1, 2, 3, 4]
[]
[1, 4, 3]
[1, 4, 3]
[1, 2, 3]
2
[1, 2, 3, 4, 5, 6]
1
[1, 2, 'three', 4]
3
[1, 3, 4]
[4, 3, 1]
[1, 3, 4]
['a', 'abc', 'abac']