python入門學習筆記(二)——列表
3.列表
3.1使用列表的值
name = ['dad','sss','ff']
print(name)
print(name[0])
print(name[-1].upper())
3.2修改列表值
name[-1] = 'aa'
print(name)
3.3新增元素
3.3.1在末尾加一個元素:append()
3.3.2在列表任意位置新增:insert()
name = ['ss',' eew ','eee']
print(name)
name.insert(1,'555')
print(name)
##
['ss', ' eew ', 'eee']
['ss', '555', ' eew ', 'eee']
3.4刪除元素
3.4.1刪除不返回值:del
name = ['ss',' eew ','eee']
print(name)
del name[0]
print(name)
3.4.2刪除末尾元素,返回值(和出棧類似):pop()
或彈出任意位置pop(x)
name = ['ss',' eew ','eee']
print(name)
x = name.pop()
print(name)
print(x)
#
['ss', ' eew ', 'eee']
['ss', ' eew ']
eee
3.4.3根據值刪除元素
remove() 和pop()類似也可以使用其值
3.5組織列表
3.5.1對列表進行永久性排序(無法恢復到原來的順序)
3.5.1.1按字母順序排序:sort()
name = ["dd","cc","xx"]
name.sort()
print(name)
#
['cc', 'dd', 'xx']
3.5.1.2按字母相反排序:給sort()引數 reverse=True
name = ["dd","cc","xx"]
name.sort(reverse=True)
print(name)
#
['xx', 'dd', 'cc']
3.5.2進行臨時排序:按特定順序輸出,保留列表原來排序sorted()
name = ["dd","cc","xx"]
print(sorted(name))
print(name)
#
['cc', 'dd', 'xx']
['dd', 'cc', 'xx']
3.5.3倒著列印列表:reverse()
name = ["dd","cc","xx"]
name.reverse()
print(name)
#
['xx', 'cc', 'dd']
3.5.4確定列表長度:len()
name = ["dd","cc","xx"]
print(len(name))
#
3