python之列表、字典、集合
生活随笔
收集整理的這篇文章主要介紹了
python之列表、字典、集合
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
列表
name = ["Alex","Eenglan","Eric"] print(name[0]) print(name[1]) print(name[2])運行如下
?
下標
name = ["Alex","Eenglan","Eric","Rain","World","Tom"] print(name[1:4]) #取下標1到下標4之間的數字,包括1,不包括4.顧頭不顧尾。 print(name[1:-1]) #取下標1到-1的值,不包括-1 print(name[::2]) #取下標0到之后所有,每隔兩個取一個 print(name[-1]) #取下標最后一個?
追加?
append
運行如下
?
?
插入? insert
name = ["Alex","Eenglan","Eric","Rain","World","Tom"] name.insert(2,"Lilei") #Lilei插入到下標為2的位置 print(name)運行如下
?
修改
name = ["Alex","Eenglan","Eric","Rain","World","Tom"] name[2]="Lilei" #修改下標是2的字符串為Lilei print(name)運行如下
?
?
刪除三種方法
name = ["Alex","Eenglan","Eric","Rain","World","Tom"] name.remove("Tom") # 刪除字符串Tom print(name)name1 = ["Alex","Eenglan","Eric","Rain","World","Tom"] del name1[-1] #刪除下標為-1列表 print(name1)name2 = ["Alex","Eenglan","Eric","Rain","World","Tom"] name2.pop() #刪除最后一個 print(name2)運行如下
?
?
擴展? extend
運行如下
?
拷貝? copy
name = ["Alex","Eenglan","Eric","Rain","World","Tom"] b = name.copy() #拷貝name的內容 print(b)運行如下
?
統計? count
name = ["Alex","Alex","Eric","Alex","World","Tom"] print(name.count("Alex")) #統計Alex有幾個運行如下
排序&反轉? sort & reverse
name = ["Alex","Lilei","Eric","1","2","3"] name.sort() #排序,ask碼排序 print(name) name.reverse() #反轉排序 print(name)運行如下
?
獲取下標? index
name = ["Alex","Lilei","Eric","1","2","3"] print(name.index("Lilei")) #獲取Lilei的下標運行如下
?
?
元組
元組和列表差不多,就是存放一組數據,只不過一旦創建不能修改,而列表可以修改
name = ("Alex","Lilei","Eric","Lilei","2","3") print(name.index("Lilei")) #獲取Lilei的下標,但是只能找到第一個 print(name.count("Lilei")) #獲取Lilei的重復次數運行如下
?
?
?
字符串操作
移出空白
msg=' asdada\n' print(msg.strip())運行如下
分割取值
msg='my name is lilei' print(msg[4:6]) print(msg[4]) print(msg[4:6:2]) #4-6范圍內每隔2個取一個運行如下
?
長度
lilei='12345' print(len(lilei)) #查看變量的長度運行如下
字符串工廠函數
class str(object):"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'."""def capitalize(self): # real signature unknown; restored from __doc__"""首字母變大寫S.capitalize() -> strReturn a capitalized version of S, i.e. make the first characterhave upper case and the rest lower case."""return ""def casefold(self): # real signature unknown; restored from __doc__"""S.casefold() -> strReturn a version of S suitable for caseless comparisons."""return ""def center(self, width, fillchar=None): # real signature unknown; restored from __doc__"""原來字符居中,不夠用空格補全S.center(width[, fillchar]) -> strReturn S centered in a string of length width. Padding isdone using the specified fill character (default is a space)"""return ""def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""從一個范圍內的統計某str出現次數S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub instring S[start:end]. Optional arguments start and end areinterpreted as in slice notation."""return 0def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__"""encode(encoding='utf-8',errors='strict')以encoding指定編碼格式編碼,如果出錯默認報一個ValueError,除非errors指定的是ignore或replaceS.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding. Default encodingis 'utf-8'. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that can handle UnicodeEncodeErrors."""return b""def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__"""S.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try."""return Falsedef expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__"""將字符串中包含的\t轉換成tabsize個空格S.expandtabs(tabsize=8) -> strReturn a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed."""return ""def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def format(self, *args, **kwargs): # known special case of str.format"""格式化輸出三種形式:形式一.>>> print('{0}{1}{0}'.format('a','b'))aba形式二:(必須一一對應)>>> print('{}{}{}'.format('a','b'))Traceback (most recent call last):File "<input>", line 1, in <module>IndexError: tuple index out of range>>> print('{}{}'.format('a','b'))ab形式三:>>> print('{name} {age}'.format(age=12,name='lhf'))lhf 12S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}')."""passdef format_map(self, mapping): # real signature unknown; restored from __doc__"""與format區別'{name}'.format(**dict(name='alex'))'{name}'.format_map(dict(name='alex'))S.format_map(mapping) -> strReturn a formatted version of S, using substitutions from mapping.The substitutions are identified by braces ('{' and '}')."""return ""def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.index(sub[, start[, end]]) -> intLike S.find() but raise ValueError when the substring is not found."""return 0def isalnum(self): # real signature unknown; restored from __doc__"""至少一個字符,且都是字母或數字才返回TrueS.isalnum() -> boolReturn True if all characters in S are alphanumericand there is at least one character in S, False otherwise."""return Falsedef isalpha(self): # real signature unknown; restored from __doc__"""至少一個字符,且都是字母才返回TrueS.isalpha() -> boolReturn True if all characters in S are alphabeticand there is at least one character in S, False otherwise."""return Falsedef isdecimal(self): # real signature unknown; restored from __doc__"""S.isdecimal() -> boolReturn True if there are only decimal characters in S,False otherwise."""return Falsedef isdigit(self): # real signature unknown; restored from __doc__"""S.isdigit() -> boolReturn True if all characters in S are digitsand there is at least one character in S, False otherwise."""return Falsedef isidentifier(self): # real signature unknown; restored from __doc__"""字符串為關鍵字返回TrueS.isidentifier() -> boolReturn True if S is a valid identifier accordingto the language definition.Use keyword.iskeyword() to test for reserved identifierssuch as "def" and "class"."""return Falsedef islower(self): # real signature unknown; restored from __doc__"""至少一個字符,且都是小寫字母才返回TrueS.islower() -> boolReturn True if all cased characters in S are lowercase and there isat least one cased character in S, False otherwise."""return Falsedef isnumeric(self): # real signature unknown; restored from __doc__"""S.isnumeric() -> boolReturn True if there are only numeric characters in S,False otherwise."""return Falsedef isprintable(self): # real signature unknown; restored from __doc__"""S.isprintable() -> boolReturn True if all characters in S are consideredprintable in repr() or S is empty, False otherwise."""return Falsedef isspace(self): # real signature unknown; restored from __doc__"""至少一個字符,且都是空格才返回TrueS.isspace() -> boolReturn True if all characters in S are whitespaceand there is at least one character in S, False otherwise."""return Falsedef istitle(self): # real signature unknown; restored from __doc__""">>> a='Hello'>>> a.istitle()True>>> a='HellP'>>> a.istitle()FalseS.istitle() -> boolReturn True if S is a titlecased string and there is at least onecharacter in S, i.e. upper- and titlecase characters may onlyfollow uncased characters and lowercase characters only cased ones.Return False otherwise."""return Falsedef isupper(self): # real signature unknown; restored from __doc__"""S.isupper() -> boolReturn True if all cased characters in S are uppercase and there isat least one cased character in S, False otherwise."""return Falsedef join(self, iterable): # real signature unknown; restored from __doc__"""#對序列進行操作(分別使用' '與':'作為分隔符)>>> seq1 = ['hello','good','boy','doiido']>>> print ' '.join(seq1)hello good boy doiido>>> print ':'.join(seq1)hello:good:boy:doiido#對字符串進行操作>>> seq2 = "hello good boy doiido">>> print ':'.join(seq2)h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o#對元組進行操作>>> seq3 = ('hello','good','boy','doiido')>>> print ':'.join(seq3)hello:good:boy:doiido#對字典進行操作>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}>>> print ':'.join(seq4)boy:good:doiido:hello#合并目錄>>> import os>>> os.path.join('/hello/','good/boy/','doiido')'/hello/good/boy/doiido'S.join(iterable) -> strReturn a string which is the concatenation of the strings in theiterable. The separator between elements is S."""return ""def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.ljust(width[, fillchar]) -> strReturn S left-justified in a Unicode string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def lower(self): # real signature unknown; restored from __doc__"""S.lower() -> strReturn a copy of the string S converted to lowercase."""return ""def lstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.lstrip([chars]) -> strReturn a copy of the string S with leading whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def maketrans(self, *args, **kwargs): # real signature unknown"""Return a translation table usable for str.translate().If there is only one argument, it must be a dictionary mapping Unicodeordinals (integers) or characters to Unicode ordinals, strings or None.Character keys will be then converted to ordinals.If there are two arguments, they must be strings of equal length, andin the resulting dictionary, each character in x will be mapped to thecharacter at the same position in y. If there is a third argument, itmust be a string, whose characters will be mapped to None in the result."""passdef partition(self, sep): # real signature unknown; restored from __doc__"""以sep為分割,將S分成head,sep,tail三部分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 notfound, return S and two empty strings."""passdef replace(self, old, new, count=None): # real signature unknown; restored from __doc__"""S.replace(old, new[, count]) -> strReturn a copy of S with all occurrences of substringold replaced by new. If the optional argument count isgiven, only the first count occurrences are replaced."""return ""def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.rfind(sub[, start[, end]]) -> intReturn the highest index in S where substring sub is found,such that sub is contained within S[start:end]. Optionalarguments start and end are interpreted as in slice notation.Return -1 on failure."""return 0def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__"""S.rindex(sub[, start[, end]]) -> intLike S.rfind() but raise ValueError when the substring is not found."""return 0def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__"""S.rjust(width[, fillchar]) -> strReturn S right-justified in a string of length width. Padding isdone using the specified fill character (default is a space)."""return ""def rpartition(self, sep): # real signature unknown; restored from __doc__"""S.rpartition(sep) -> (head, sep, tail)Search for the separator sep in S, starting at the end of S, and returnthe part before it, the separator itself, and the part after it. If theseparator is not found, return two empty strings and S."""passdef rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""S.rsplit(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string, starting at the end of the string andworking to the front. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified, any whitespace stringis a separator."""return []def rstrip(self, chars=None): # real signature unknown; restored from __doc__"""S.rstrip([chars]) -> strReturn a copy of the string S with trailing whitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__"""以sep為分割,將S切分成列表,與partition的區別在于切分結果不包含sep,如果一個字符串中包含多個sep那么maxsplit為最多切分成幾部分>>> a='a,b c\nd\te'>>> a.split()['a,b', 'c', 'd', 'e']S.split(sep=None, maxsplit=-1) -> list of stringsReturn a list of the words in S, using sep as thedelimiter string. If maxsplit is given, at most maxsplitsplits are done. If sep is not specified or is None, anywhitespace string is a separator and empty strings areremoved from the result."""return []def splitlines(self, keepends=None): # real signature unknown; restored from __doc__"""Python splitlines() 按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表,如果參數 keepends 為 False,不包含換行符,如 果為 True,則保留換行符。>>> x'adsfasdf\nsadf\nasdf\nadf'>>> x.splitlines()['adsfasdf', 'sadf', 'asdf', 'adf']>>> x.splitlines(True)['adsfasdf\n', 'sadf\n', 'asdf\n', 'adf']S.splitlines([keepends]) -> list of stringsReturn a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keependsis given and true."""return []def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__"""S.startswith(prefix[, start[, end]]) -> boolReturn True if S starts with the specified prefix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.prefix can also be a tuple of strings to try."""return Falsedef strip(self, chars=None): # real signature unknown; restored from __doc__"""S.strip([chars]) -> strReturn a copy of the string S with leading and trailingwhitespace removed.If chars is given and not None, remove characters in chars instead."""return ""def swapcase(self): # real signature unknown; restored from __doc__"""大小寫反轉S.swapcase() -> strReturn a copy of S with uppercase characters converted to lowercaseand vice versa."""return ""def title(self): # real signature unknown; restored from __doc__"""S.title() -> strReturn a titlecased version of S, i.e. words start with title casecharacters, all remaining cased characters have lower case."""return ""def translate(self, table): # real signature unknown; restored from __doc__"""table=str.maketrans('alex','big SB')a='hello abc'print(a.translate(table))S.translate(table) -> strReturn a copy of the string S in which each character has been mappedthrough the given translation table. The table must implementlookup/indexing via __getitem__, for instance a dictionary or list,mapping Unicode ordinals to Unicode ordinals, strings, or None. Ifthis operation raises LookupError, the character is left untouched.Characters mapped to None are deleted."""return ""def upper(self): # real signature unknown; restored from __doc__"""S.upper() -> strReturn a copy of S converted to uppercase."""return ""def zfill(self, width): # real signature unknown; restored from __doc__"""原來字符右對齊,不夠用0補齊S.zfill(width) -> strPad a numeric string S with zeros on the left, to fill a fieldof the specified width. The string S is never truncated."""return ""def __add__(self, *args, **kwargs): # real signature unknown""" Return self+value. """passdef __contains__(self, *args, **kwargs): # real signature unknown""" Return key in self. """passdef __eq__(self, *args, **kwargs): # real signature unknown""" Return self==value. """passdef __format__(self, format_spec): # real signature unknown; restored from __doc__"""S.__format__(format_spec) -> strReturn a formatted version of S as described by format_spec."""return ""def __getattribute__(self, *args, **kwargs): # real signature unknown""" Return getattr(self, name). """passdef __getitem__(self, *args, **kwargs): # real signature unknown""" Return self[key]. """passdef __getnewargs__(self, *args, **kwargs): # real signature unknownpassdef __ge__(self, *args, **kwargs): # real signature unknown""" Return self>=value. """passdef __gt__(self, *args, **kwargs): # real signature unknown""" Return self>value. """passdef __hash__(self, *args, **kwargs): # real signature unknown""" Return hash(self). """passdef __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__"""str(object='') -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to 'strict'.# (copied from class doc)"""passdef __iter__(self, *args, **kwargs): # real signature unknown""" Implement iter(self). """passdef __len__(self, *args, **kwargs): # real signature unknown""" Return len(self). """passdef __le__(self, *args, **kwargs): # real signature unknown""" Return self<=value. """passdef __lt__(self, *args, **kwargs): # real signature unknown""" Return self<value. """passdef __mod__(self, *args, **kwargs): # real signature unknown""" Return self%value. """passdef __mul__(self, *args, **kwargs): # real signature unknown""" Return self*value.n """pass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __ne__(self, *args, **kwargs): # real signature unknown""" Return self!=value. """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passdef __rmod__(self, *args, **kwargs): # real signature unknown""" Return value%self. """passdef __rmul__(self, *args, **kwargs): # real signature unknown""" Return self*value. """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" S.__sizeof__() -> size of S in memory, in bytes """passdef __str__(self, *args, **kwargs): # real signature unknown""" Return str(self). """pass View Code常用的,控制變量的類型
?
轉載于:https://www.cnblogs.com/Llblogs/p/5971675.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python之列表、字典、集合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Shell until循环
- 下一篇: Freemarker 内置函数 数字、字