python之再学习----简单的列表(2)

# filename:python2.24.py
# author:super
# date:2018-2-24

print('today to learn how to add/delete/change the list')
# 学习list的append, insert, del, remove, pop 方法, 补充list->str, str->list方法
# 可以通过指定列表名和要修改的参数的元素的索引, 再指定该元素的新值
motocycles = ['honda', 'yamaha', 'suzuki']
print(motocycles)
motocycles[0] = 'ducati'
print(motocycles)
# 可以在现有的列表中使用append, 在列表的最后加入元素
motocycles.append('ducati')
print(motocycles)
# 也可以建立一个空的列表, 一直使用append来一直添加元素
# print('the new list is:'+motocycle) 直接使用这个时报错, 因为list不能作为str输入 ,会有:must be str, not list错误
# 可以改为print('the new list is:'+str(motocycle)) 把list改为str,在print 就可以一直输出
motocycle = []
motocycle.append('honda')
motocycle.append('yamaha')
motocycle.append('suzuki')
print('the new list is:'+str(motocycle))
# 可以使用insert在列表中的任何位置添加新元素(需要指定新的索引和值)
motocycles.insert(1, 'ducati2')
print(motocycles)
motocycles.insert(2, 'ducati3')
print(motocycles)
# 如果知道要删除的元素的索引,可以用del语句来直接删除
del motocycles[0]
print(motocycles)
# 可以使用pop的方法来删除list中的值,pop后面也可以加入相应的索引
# 他跟del的方法区别在于:
# del 删除的元素不可以用, 而用pop的方法其实是弹出, 可以用一个变量去接受这个弹出的值
# 如果这个值就是想删除 , 就用del, 如果还想用 , 可以用pop
popped_motorcycle = motocycles.pop(1)
print(motocycles)
print(popped_motorcycle)
# 当你只知道值的内容的时候, 可以用remove,另外 remove和pop一样, 可以用一个变量去接
motocycles.remove('ducati2')
print(motocycles)

# practice
name_list = ['aa', 'bb', 'cc']
print(name_list)
print(str(name_list[0])+' can not join the dinner')
name_list[0] = 'new aa'
print(name_list)
for i in range(len(name_list)):
print(str(name_list[i])+' ,please remember to join the dinner')
name_list.insert(0, 'dd')
name_list.insert(2, 'ee')
name_list.append('ff')
print(name_list)
print("sorry , now dont have so many people can join the dinner, i only can invite two people")
while len(name_list) > 2:
print('this time the one is poped :'+name_list.pop())
print(name_list)
del name_list[0]
print(name_list)
del name_list[0]
print(name_list)

# 字符串转列表
str1 = "hi hello world"
print(str1.split(" "))
# 列表转字符串
l = ["hi", "hello", "world"]
print(" ".join(l))



# 关于对列表进行排序
# 用sort会永久改变List的顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# 用sort(reverse=True)会按照字母倒序排序, 也是永久改变列表顺序的
cars.sort(reverse=True)
print(cars)
# reverse不对列表的字母大小进行比较, 是直接从列表的最后一个开始,倒序打印
cars.reverse()
print(cars)
posted @ 2018-02-24 09:34  super-JAVA  阅读(139)  评论(0编辑  收藏  举报