#声明列表
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)