#聲明列表
Marvel_Heroes = ['jack', 'tom', 'lucy', 'superman', 'ironman']
Computer_brands = []
print(id(Marvel_Heroes))
print(id(Computer_brands)) #定義空列表
#遍歷
for name in Marvel_Heroes:
print(name)
#獲取第一個元素
print(Marvel_Heroes[0])
#獲取最後一個元素
print(Marvel_Heroes[-1])
print(Marvel_Heroes[len(Marvel_Heroes)-1])
#判斷是否存在
result = 'jack' in Marvel_Heroes
print(result)
#切片操做
print(Marvel_Heroes[1:3]) #包前不包後
#反向
print(Marvel_Heroes[-1::-2])
#增:
# append(): 在末尾追加
brands = ['hp', 'thinkpad']
brands.append('dell')
print(brands)
# extend():把字符串一個一個拆了再追加,至關於列表合併
names = []
names.extend('dell') #示範
print(names)
names.extend(brands) #正確的使用
print(names)
# insert():指定位置插入,原來的數據日後移動
brands = ['hp', 'thinkpad']
brands.insert(1, 'dell')
print(brands)
#刪
brands = ['hp', 'thinkpad', 'lenovo', 'huawei', 'dell', 'mac', 'apple', 'hp', 'hp', 'acer']
l = len(brands)
i = 0
while i < l:
if 'hp' == brands[i] or 'mac' == brands[i]:
del brands[i]
l -= 1
i -= 1 #防止出現連續的狀況,漏刪了後面內容
i += 1
print(brands)
#防止漏刪法2
brands = ['hp', 'thinkpad', 'lenovo', 'huawei', 'dell', 'mac', 'apple', 'hp', 'hp', 'acer']
l = len(brands)
i = 0
while i < l:
if 'hp' != brands[i] and 'mac' != brands[i]:
i += 1
else:
del brands[i]
l -= 1
print(brands)
#防止漏刪法3
brands = ['hp', 'thinkpad', 'lenovo', 'huawei', 'dell', 'mac', 'apple', 'hp', 'hp', 'acer']
l = len(brands)
i = 0
while i < l:
if 'hp' == brands[i] or 'mac' == brands[i]:
del brands[i]
l -= 1
continue #防止漏刪了連續的內容
i += 1
print(brands)
#改
brands[5] = 'xiaomi'
print(brands)
import random
random_list = random.sample(range(0, 100), 6)
print(random_list)
list_sum = sum(random_list)
print(list_sum)
random_list = sorted(random_list) #默認爲升序,sorted(random_list, reverse = False)
print(random_list)
hotpot_list = ['海底撈', '呷哺呷哺', '熱辣一號', '寬板凳']
print(hotpot_list)
print('------------------------------------------------------------')
hotpot_list.append('張亮麻辣燙')
print(hotpot_list)
print('------------------------------------------------------------')
result = hotpot_list.remove('張亮麻辣燙') #移除列表中第一次出現的元素,若是沒有找到要刪除的元素則報異常
print(result) #沒有返回值
print(hotpot_list)
print('------------------------------------------------------------')
hotpot_list.append('張亮麻辣燙')
result = hotpot_list.pop() #彈棧,移除列表中的最後一個元素,返回值是刪除的那個元素
print(result) #返回值是最後一個元素
print(hotpot_list)
result = hotpot_list.pop(2)
print(result)
print(hotpot_list)
print('------------------------------------------------------------')
hotpot_list.reverse() #將列表倒序
print(hotpot_list)
print('------------------------------------------------------------')
hotpot_list.clear()
print(hotpot_list)
l1 = ['a', 'abc', 'jk', 'poop']
for value in l1:
print(value)
for index, value in enumerate(l1):
print(index, value)
###例子:冒泡排序
numbers = [5, 7, 8, 9, 4, 2, 3, 1, 6, 10]
#numbers = sorted(numbers)
print ('排序前列表 :',numbers)
for i in range(len(numbers)):
temp = numbers[i]
for index, value in enumerate(numbers[i:]):
if temp > value:
numbers[index + i] = temp
temp = value
numbers[i] = temp
print('冒泡排序後列表:',numbers)