日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python序列数据类型_Python 数据类型 之 序列类型

發布時間:2023/12/4 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python序列数据类型_Python 数据类型 之 序列类型 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

序列:表示索引為非負整數的有序對象集合,所有序列都支持迭代

序列類型有:字符串,列表,元組 三種

字符串也是一種序列

列表和元組是任意python對象的序列或叫有序集合

字符串和元組不可變序列,列表支持插入、刪除和替換元素

序列類型的通用操作方法:

1. 索引運算。s[i] [i]可以使用負數,即倒著取值

2. 切片運算。s[i:j] ,切片后會生成新的對象

3. 擴展切片。s[i:j:stride],指定步長值

obj[1:] , obj[-2:-1],obj[0:6:2]

字符串 str

常用操作:

索引

切片

移除空白 obj.strip()

分割 obj.split()

長度 len(obj) , obj.__len__()

返回索引 obj.index(),obj.find()

輸出位置 obj.center(),obj.ljust(),obj.rjust()

...

__len__(self, /)

Return len(self).| capitalize(...) '''首字母大寫'''

| S.capitalize() ->str|

|Return a capitalized version of S, i.e. make the first character| have upper case andthe rest lower case.>>> 'test string'.capitalize()'Test string'

|center(...)| S.center(width[, fillchar]) ->str| Return S centered in a string of length width. Padding is

| done using the specified fill character (default isa space)>>> print(8*'#')########

>>> 'test'.center(20,'*')'********test********'

|ljust(...)| S.ljust(width[, fillchar]) ->str>>> 'test'.ljust(10,'<')

Out[61]: 'test <<<<<'

|rjust(...)| S.rjust(width[, fillchar]) ->str>>> 'test'.rjust(10,'>')

Out[59]: '>>>>> test'

| count(...) '''統計字符出現的個數'''

| S.count(sub[, start[, end]]) ->int>>> 'test string'.count('s')

In [8]: 'test string'.count('s',1,4)| encode(...) '''指定字符編碼'''

| S.encode(encoding='utf-8', errors='strict') ->bytes|

| Encode S using the codec registered for encoding. Default encoding is 'utf-8'.>>> '中文'.encode('gbk')

b'\xd6\xd0\xce\xc4'

'''utf8可以直接轉成gbk(內部實現通過unicode)'''

| endswith(...) '''判斷是否以某個字符后綴結束'''

| S.endswith(suffix[, start[, end]]) ->bool|

| Return True ifS ends with the specified suffix, False otherwise.>>> 'test string'.endswith('t',1,4)

True|startswith(...)| S.startswith(prefix[, start[, end]]) ->bool| expandtabs(...) '''將tab轉換成空格'''

| S.expandtabs(tabsize=8) ->str>>> 'te\tst'.expandtabs()'te st'

|format(...)| S.format(*args, **kwargs) ->str>>> info='my name is {0}, sex {1}'

>>> info.format('Jack','male')'my name is Jack, sex male'

>>> info='my name is {Name}, sex {Sex}'

>>> info.format(Name='Lucy',Sex='female')'my name is Lucy, sex female'

| find(...) '''返回字符的索引, 如有多個,只返回第一個字符的索引,不存在返回-1'''

| S.find(sub[, start[, end]]) ->int|

| Return the lowest index in S where substring sub isfound,| such that sub iscontained within S[start:end].| Return -1on failure.>>> 'test string'.find('t',2,6)| index(...) '''返回字符的索引, 如有多個,只返回第一個字符的索引,不存則報異常'''

| S.index(sub[, start[, end]]) ->int|

| Like S.find() but raise ValueError when the substring is notfound.>>> 'test string'.index('a')

ValueError: substringnotfound>>> 'test string'.find('a')-1

|rfind(...)| S.rfind(sub[, start[, end]]) ->int|rindex(...)| S.rindex(sub[, start[, end]]) ->int|isalnum(...)| S.isalnum() ->bool|isalpha(...)| S.isalpha() ->bool|isdecimal(...)| S.isdecimal() ->bool|isdigit(...)| S.isdigit() ->bool|islower(...)| S.islower() ->bool| Return True if all cased characters in S are lowercase and there is

| at least one cased character inS, False otherwise.|isupper(...)| S.isupper() ->bool| Return True if all cased characters in S are uppercase and there is

| at least one cased character inS, False otherwise.>>> 'TEST STRING'.isupper()

True|upper(...)| S.upper() ->str| istitle(...) '''判斷是否所有單詞首字母大寫'''

| S.istitle() ->bool|

| Return True if S is a titlecased string and there isat least one| character inS>>> 'Test String'.istitle()

True|title(...)| S.title() ->str|

|Return a titlecased version of S>>> 'test string'.title()'Test String'

| join(...) '''指定連接符將序列的元素連接起來'''

| S.join(iterable) ->str|

| Return a string which is the concatenation of the strings in the iterable. The separator between elements isS.>>> ls=['a','b','c']>>> '-'.join(ls)'a-b-c'

| split(...) '''將字符串分割,形成列表, 不指定分隔符默認為空格'''

| S.split(sep=None, maxsplit=-1) ->list of strings|

| Return a list of the words inS, using sep as the| delimiter string. If sep is notspecified, any whitespace string| isa separator.>>> 'test string'.split()

['test', 'string']>>> 'test=string'.split('=')

['test', 'string']>>> 'this is test string'.split(maxsplit=2)

['this', 'is', 'test string']| rsplit(...) '''從右到左進行分割'''

| S.rsplit(sep=None, maxsplit=-1) ->list of strings| strip(...) '''去除首尾的字符,默認為空格'''

| S.strip([chars]) ->str|

| Return a copy of the string S with leading andtrailing|whitespace removed.| If chars is given and not None, remove characters inchars instead.>>> 'test string'.strip()'test string

>>> '### test string ###'.strip('#')'test string'

>>> '### test string ###'.lstrip('#')'test string ###

>>> '### test string ###'.rstrip('#')'### test string'

|partition(...)| S.partition(sep) ->(head, sep, tail)|

| Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not

| found, return S andtwo empty strings.>>> '### test ***'.partition('test')

('###', 'test', '***')|rpartition(...)| S.rpartition(sep) ->(head, sep, tail)|replace(...)| S.replace(old, new[, count]) ->str>>> 'abc'.replace('b','2')'a2c'

| swapcase(...) '''大寫轉小寫,小寫轉大寫'''

| S.swapcase() ->str|translate(...)| S.translate(table) ->str| maketrans(x, y=None, z=None, /)| Return a translation table usable forstr.translate().>>> intab='abcd'

>>> outtab='1234'

>>> table=str.maketrans(intab,outtab)>>> 'abcdefg'.translate(table)'1234efg'

help(str)

列表 list

創建列表:

ls=['a','b','c'] 或 list(['a','b','c']) 或 list(('a','b','c'))

常用操作:

索引

切片

追加 obj.append(),obj.extend()

插入 obj.insert()

刪除 __delitem__(),obj.remove(),obj.pop()

長度 len(obj)

返回索引 obj.index()

循環 for,while

包含 in

注意:append(),extend(),insert(),remove(),pop() 等都是直接修改列表,不會產生新的對象,不能對列表操作這些方法后賦值給另外一個變量,例如:ls2=ls1.append(),如要賦值可以使用__add__()

| __contains__(self, key, /)| Return key inself.| __delitem__(self, key, /) '''刪除指定位置的元素'''

|Delete self[key].>>> ls=['a','b','c']>>> ls.__delitem__(1)>>> print(ls)

['a', 'c']| __len__(self, /) '''統計列表的長度(即元素的個數)'''

|Return len(self).| append(...) '''在末尾追加單個元素'''

| L.append(object) -> None --append object to end|clear(...)| L.clear() -> None -- remove all items fromL| copy(...) '''淺拷貝'''

| L.copy() -> list --a shallow copy of L| count(...) '''統計某個元素的出現個數'''

| L.count(value) -> integer -- returnnumber of occurrences of value>>> ls=['h','e','l','l','o']>>> ls.count('l')2

| extend(...) '''從序列里擴展元素'''

| L.extend(iterable) -> None -- extend list by appending elements fromthe iterable>>> ls=['h','e','l','l','o']>>> ls.extend('world')>>> print(ls)

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']| index(...) '''獲取某個元素的索引,如有多個,只返回第一個'''

| L.index(value, [start, [stop]]) -> integer -- returnfirst index of value.| Raises ValueError if the value is notpresent| insert(...) '''在指定的索引遷插入'''

| L.insert(index, object) --insert object before index| pop(...) '''刪除指定位置的元素并獲取到這個元素,默認為最后一個元素'''

| L.pop([index]) -> item -- remove and returnitem at index (default last).| Raises IndexError if list is empty or index isout of range.>>> ls=['a','b','c',]>>> ls.pop(2)'c'

>>>ls.pop()'b'

| remove(...) '''刪除指定的元素'''

| L.remove(value) -> None --remove first occurrence of value.| Raises ValueError if the value is notpresent.>>> ls=['a','b','c',]>>> ls.remove('c')| reverse(...) '''倒序'''

| L.reverse() -- reverse *IN PLACE*

>>> ls=['a','b','c']>>>ls.reverse()>>> print(ls)

['c', 'b', 'a']| sort(...) '''對列表內的元素進行排序, 可以指定key'''

| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

>>> ls = ['Chr1-10.txt','Chr1-1.txt','Chr1-2.txt','Chr1-14.txt','Chr1-3.txt','Chr1-20.txt','Chr1-5.txt']>>> ls.sort(key=lambda d : int(d.split('-')[-1].split('.')[0]))>>> print(ls)

['Chr1-1.txt', 'Chr1-2.txt', 'Chr1-3.txt', 'Chr1-5.txt', 'Chr1-10.txt', 'Chr1-14.txt', 'Chr1-20.txt']

help(list)

元組 tuple

創建元組:

tp=('a','b','c') 或 tp=tuple((1,2,3)) 或 tp=tuple(['x','y','z'])

常用操作:

索引

切片

迭代 for / while

長度 len(obj)

包含 in / not in

注意:元組本身是不可變對象 ,長度固定,所以代碼更安全。 所謂的“不變”是指元組的每個元素指向永遠不變,元組本身不可變,但元組內嵌套了可變類型的元素,此元素的修改不會返回新元組.

即:

元組的元素只讀,不可修改

元組中元素的元素可以修改

如:

>>> tp=(1,'a',['x'])

>>> tp[2].append('y')

>>> print(tp)

(1, 'a', ['x', 'y'])

| __add__(self, value, /)| Return self+value.>>> tp=(1,2,3)>>> tp.__add__(('a','b','c'))

(1, 2, 3, 'a', 'b', 'c')| __len__(self, /)|Return len(self).|count(...)| T.count(value) -> integer -- returnnumber of occurrences of value|index(...)| T.index(value, [start, [stop]]) -> integer -- returnfirst index of value.| Raises ValueError if the value is not present.

help(tuple)

提示:創建元組或列表后面最好帶逗號 如 ls=[1,2,3,] 、tp=(1,2,3,)

總結

以上是生活随笔為你收集整理的python序列数据类型_Python 数据类型 之 序列类型的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。