Python3 通用序列操作

2021-08-21 04:36:30 字數 2619 閱讀 1538

第乙個原素索引從0開始

numbers=[1,2,3,4,5,6,7,8,9]

print(numbers)

>>[1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers)

print(numbers[7:10]) #索引10指的是第11個元素,它並不存在。

索引為負,表示從列表末尾開始數:

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[-3:-1])

>>[8, 9]

表示取列表倒數第3到倒數第乙個(不包括倒數第乙個)原素的切片。

(區間為前閉後開)

如果想包含最後乙個元素,可以使用以下方法:

(如果切片結束於結尾,可以省略第二個索引)

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[-3:])

>>[8, 9, 10]

(如果切片開始於序列開頭,可以省略第乙個索引)

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[:3])

>>[1, 2, 3]

指定步長

第三個引數為步長,

步長為正,表示方向為從左到右

步長為負,表示方向為從右到左。

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[::2])

>>[1, 3, 5, 7, 9] #從頭到尾,步長為2 第三個引數為步長

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[::-2])

>>[10, 8, 6, 4, 2]

numbers=[1,2,3,4,5,6,7,8,9,10]

print(numbers[10:0:-2])

>>[10, 8, 6, 4, 2]

運用加法來拼接序列

只能同型別相加,不同型別的不能直接用+號相加。

[1,2,3]+[4,5,6]

>>[1, 2, 3, 4, 5, 6]

"hello,"+"world"

>>'hello,world'

"hello,"

*5>>'hello,hello,hello,hello,hello,'

[1]*5

>>[1,1,1,1,1,]

none、空列表和初始化

空列表是使用不包含任何內容的兩個方括號([ ])表示的.

如果要建立乙個可包含10個元素的列表,但沒有任何有用的內容,可以向上面那樣使用[1]*10

但更準確的做法是使用[0]*10.

然而,有些情況下可能想使用「什麼都沒有」的值,此時可以使用none.

在python中,none表示什麼都沒有。

[none]*5

>>[none, none, none, none, none]

要檢查特定的值是否包含在序列中,可使用運算子in.

滿足時返回true,不滿足時返回false.這樣的運算稱為布林運算。

內建函式len、min、max.

len() 返回序列中包含的元素個數。

min()和max() 分別返回序列中的最大值和最小值。

numbers=[100,2,50]

print("len is:{}".format(len(numbers)))

print("min is:{}".format(min(numbers)))

print("max is:{}".format(max(numbers)))

>> len is:3

min is:2

max is:100

python3中通用的序列操作

python3中包含有4種內建的序列 列表 元組 字串 unicode字串 buffer物件 xrange物件在2中存在,3中好像沒有了 通用的序列操作 所有的序列型別都可以進行的操作 索引 切片 拼接 複製多次 成員資格檢查in not in 序列長度 查詢最大元素 查詢最小元素 內建函式的功勞 ...

python通用序列操作 python序列的使用

序列之通用操作 pytho中,最基本的資料結構就是序列。什麼是序列 numbers 1,2,3,4,5,6,7,8,9,0 greeting u hello,world names alice tom ben john python內建序列種類 共有6種 列表,元組,字串,unicode字串,buf...

python3通過pymongo操作mongoDB

2,增刪改查 mongodb預設開啟的埠號是27017 import pymongo 連線本地mongo服務 client bendi pymongo.mongoclient db bendi client bendi db name col bendi db bendi col name impo...