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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章