Python_列表简介

1. 列表的定义

# _*_ coding:utf8 _*_
# 想要注释 就得必须进行编码格式的指定

bicycles = ['trek','car','taxi']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[1].upper())
print(bicycles[-1])
# -1代表返回倒数第一个 -2 代表返回倒数第二个以此类推
print(bicycles[-2])

message = ' my first cycle is '+bicycles[0]
print(message)

2. 列表的替换与插入

# _*_ coding:utf8 _*_
motorcycles = ['honda','yamaha',"suzukui"]
print(motorcycles)
# 将列表中第一个元素替换成
motorcycles[0]='yjz'
print(motorcycles)

# 在列表中添加元素
motorcycles.append("hahah")
print(motorcycles)

motorcycle=[]
motorcycle.append("heihie")
motorcycle.append("haha")
motorcycle.append("hehehe")
print(motorcycle)

# 在列表中任意位置插入元素 insert() 根据角标/索引

motorcycle.insert(0,"nihao")
print(motorcycle)

3. 列表的删除操作

# _*_ coding:utf8 _*_
waters = ["gw","bw","nw","ww"]


print(waters)

# 使用del语句删除 首先的知道元素的索引
del waters[1]
print(waters)

# 使用pop方法进行删除 这个删除的是列表中末尾的元素,并且可以将改删除的元素重新赋值给变量
value = waters.pop()
print(value)
print(waters)

# 使用pop 可以删除列表中任意元素 是通过角标的,此索引不能大于列表元素个数-1
last_values = waters.pop(0)
print(last_values)
print(waters)

# 根据值删除元素 remove()
values = ['one','two','three','four']
values.remove('one')
print(values)
value = 'two'
# 通过变量来告知列表中要删除那个元素
values.remove(value)
print(value+str(values))

4. 列表的排序操作和获取列表的长度

# _*_ coding:utf8 _*_

cars = ['bm','ad','lbjn','lh','fll']

# sort(),永久性排序  默认情况下是按字母排序;  reverse=True 是按字母顺序反顺序排列
cars.sort()
print(cars)
# ['ad', 'bm', 'fll', 'lbjn', 'lh']

cars.sort(reverse=True)
print(cars)
# ['lh', 'lbjn', 'fll', 'bm', 'ad']


# 使用sorted()进行临时排序
sorteds = ['zq','zl','yhn','zd','tzz','an']
print(sorteds)

# 临时排序 让你以特定的顺序去排序,同时不影响原有列表的排序
print(sorted(sorteds))
print(sorted(sorteds,reverse=True))
print(sorteds)

# 倒着打印列表 reverse()
sorteds.reverse()
print(sorteds)

# 确认列表的长度 len()
values =len(sorteds)
print(values)

猜你喜欢

转载自blog.csdn.net/dashingqi/article/details/80792260