# access items
lst = ["apple","banana","cherry"] #生成一个有某某内容的list
# access random item
import random
lst1 = [random.randint(1, 100) for i in range(10)] # 生成一个有10个随机值的list
# print lst
for i1 in lst:
print(i1, end=' ')
cout = len(lst)
for i2 in range(len(lst)):
print(lst[i2], end=' ')
# reverse lst
for i3 in range(len(lst)//2): # 列表前后顺序互换
lst[i3],lst[-1-i3] = lst[-1-i3],lst[i3]
# add item
lst.insert(0,"durian") # 0为索引数,在某处插入
lst.append("fig") #最好使用append
lst.append( input() )
#copy
new_lst = lst.copy
new_lst = list(lst)
new_lst = lst[:] # 以上三个是浅拷贝(shallow copy),对于list里面的某些元素会传址
# deep copy
import copy
new_lst = copy.deepcopy(lst) # 创建一个新的列表,改变新的完全不会改变原列表
#sort python自带的排序
lst.sort() # change lst1 itself
newlst2 = sorted(lst1) # do not change lst1
# premiere operation 高阶操作
print(lst[:]) # include all element in lst
print(lst[::-1]) # reverse all element in lst
print(lst[::2]) # even element
print(lst[1::2]) # odd element
print(lst[3::]) # from 3 to the end
print(lst[3:6:]) # [3,6)
print(lst[:100:]) # first 100th element, auto cut off 自动截断,不会溢出
print(lst[100:]) # the elements after 101th element, auto cut off 自动截断,不会溢出
print(lst[100]) # constrain by len(list) 超出范围无法执行
# remove item
lst.remove("fig") # remove first content in lst 只能移除第一个该内容
lst.pop() # remove the last element
lst.pop(i) # remove the (i+1)th element
lst.clear()
del lst[0]
del lst # the memory come back the time the lst is not defined
python对list的操作
最新推荐文章于 2023-03-04 03:04:53 发布