基本数据类型

一、整数类型(int)

  32位机器,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

  64位机器,整数的位数是64位,取值范围位-2**63~2**63-1,即-9223372036854775808~9223372036854775807

  bit_lenth():当十进制用二进制表示时,最少使用的位数

  1. a = 6
  2. b = 10
  3. c = 100
  4. print(a.bit_length())
  5. print(b.bit_length())
  6. print(c.bit_length())
  7. #输出结果:3,4,7

二、布尔值类型(bool)

  字符串转化位布尔值:bool(str),当字符串为空字符串,转化为False,否则转化为True

  1. a = 'afds,bnk'
  2. b = ''
  3. c = ' '
  4. print(bool(a),bool(b),bool(c))
  5. #输出结果:True,False,True
  1. a = ''
  2. if a:
  3. print('正确')
  4. else:
  5. print('错误')
  6. #输出结果:错误

三、字符串类型(str):对字符串进行操作无法改变原字符串

  1、索引:索引(下标、index)从0开始,即第一个元素的索引为0,也可以从后面开始索引,最后一个元素的索引为-1

  1. a = 'afhd,jhg:vnv'
  2. print(a[0],a[4],a[-1],a[-4])
  3. #输出结果:a , v :

  2、切片:[起始位置:结束位置:步长] ,特点:步长可以为空,默认为1;a[0:]表示从第1个元素切到最后1个元素;a[-1:]

     使用方法:先确定第一个切片的下标,然后确定最后一个切片的下标,正切则步长用正数表示,反切则步长用负数表示

  1. a = '你好,欢迎来到python世界!'
  2. #打印你好
  3. print(a[0:2])
  4. print(a[:-14])
  5. #打印python
  6. print(a[7:13])
  7. print(a[-9:-3])
  8. #打印好欢来
  9. print(a[1:6:2])
  10. print(a[-15:-10:2])
  11. #打印届nhy
  12. print(a[-2:-9:-2])
  13. print(a[14:7:-2])

  3、首字母大写:a.capitalize()

  1. a = 'abc'
  2. print(a.capitalize())
  3. #输出:Abc

  4、大小写翻转:a.swapcase()

  1. a = 'abC'
  2. print(a.swapcase())
  3. #输出:ABc

  5、每个单词的首字母大写:a.title(),以非英文字母为间隔,每个单词的首字母大写

  1. a = 'abc:fh,dg dsa .das'
  2. print(a.title())
  3. #输出:Abc:Fh,Dg Dsa .Das

  6、内容居中,空白处填充:a.center(长度,'填充内容'),填充内容为空则默认用空格填充,优先填充右边

  1. a = ''
  2. print(a.center(10,'*'))
  3. #输出结果:**12345***

  7、将tab键变成空格:如果tab键前面的字符长度不足8个,则将tab键变成空格,使长度变成8;如果tab键前面的字符长度>=8,则将将tab键变成空格,使长度变成16

  1. a = "hqwe\t"
  2. print(a.expandtabs())
  3. #输出结果:hqwe四个空格
  4. a = "abcdefgh\t"
  5. print(a.expandtabs())
  6. #输出结果:abcdehgh八个空格

  8、判断以.....开头、以......结尾:a.startswith('元素',起始下标,结束下标),起始下标、结束下标可以不填,则默认为整个字符串;a.endswith('元素',起始下标,结束下标),其中‘元素’可以为一个字母或多个字母

  1. a = 'svxcbdfsdgh'
  2. print(a.startswith('s',))
  3. print(a.startswith('s',1,3))
  4. print(a.startswith('s',0,3))
  5. print(a.endswith('h'))
  6. print(a.endswith('h',-1))
  7. print(a.endswith('h',-1,11))
  8. #输出结果:
  9. #True
  10. #False
  11. #True
  12. #True
  13. #True
  14. #True

  9.计算字符串中出现元素的个数:a.count('元素',起始下标,结束下标),起始下标、结束下标可以不填,则默认为整个字符串

  1. a = 'svxcbsdfsdgh'
  2. print(a.count('s'))
  3. print(a.count('s',0,6))
  4. #输出结果:
    #3
    #2

  10、寻找字符串中的元素是否存在:a.find('元素',起始下标,结束下标),找到则返回元素的索引(只寻找第一个匹配的元素),找不到则返回-1,元素可以为一个字母或多个字母

                  a.index('元素',起始下标,结束下标),找到则返回元素的索引(只寻找第一个匹配的元素),找不到则报错,元素可以为一个字母或多个字母

  1. a = 'abcabcabc'
  2. print(a.find('bc'))
  3. print(a.index('abc'))
  4. print(a.find('c',3,6))
  5. print(a.find('cb'))
  6. print(a.index('ca',0,2))
  7. #输出:
  8. #
  9. #
  10. #
  11. #-1
  12. #报错

  11、切割:a.spilt('元素',次数),被切割的元素会消失,次数为切割次数,次数可以不填,默认全部切割

  1. a = 'abc abc abc'
  2. print(a.split('b'))
  3. print(a.split('b',1))
  4. print(a.split(' '))
  5. #输出结果:
  6. #['a', 'c a', 'c a', 'c']
  7. #['a', 'c abc abc']
  8. #['abc', 'abc', 'abc']

  12.代替:a.replace('旧元素','新元素',次数),次数为替代的次数,次数可以不填,默认全部替代

  1. a = 'abcahg123aa'
  2. print(a.replace('a','w'))
  3. print(a.replace('a','w',2))
  4. #输出结果:
  5. #wbcwhg123ww
  6. #wbcwhg123aa

  13、判断是否以字母或数字组成:a.isalnum();判断是否以字母组成:a.isalpha();判断是否以字母组成:a.isdigit()

  1. a = 'asd123'
  2. print(a.isalnum())
  3. print(a.isalpha())
  4. print(a.isdigit())
  5. #输出结果:
  6. #True
  7. #False
  8. #False

  14、消除:a.strip('可迭代对象'),从头尾开始清除可迭代对象,遇到非迭代对象则停止

       a.lstrip('可迭代对象'),从左边消除可迭代对象,遇到非迭代对象则停止

          a.rstrip('可迭代对象'),从右边消除可迭代对象,遇到非迭代对象则停止

  1. a = 'safg31342fhsdf'
  2. print(a.strip('sahf'))
  3. #输出:g31342fhsd
  4. print(a.lstrip('sfd'))
  5. #输出:afg31342fhsdf
  6. print(a.rstrip('adf'))
  7. #输出:safg31342fhs

  

  15、格式化输出:三种方式

    方式一:a = 'name:{},sex:{},hobbie:{}'.format('a','b','c'),必须一一对应

    方式二:a = 'name:{0},sex:{1},hobbie:{2},job:{1}'.format('a','b','c'),不用一一对应,但需要按顺序

    方式三:a = 'name:{name},sex:{age},hobbie:{sex}:job:{sex}'.format('name = a','age = b','sex = c'),不用一一对应,也不用按顺序

  1. a = 'name:{},sex:{},hobbie:{}'.format('Peter','man','basketball')
  2. b = 'name:{0},sex:{2},hobbie:{1},name:{0}'.format('Peter','basketball','man')
  3. c = 'name:{n},sex:{s}.hobbie:{h},name:{n}'.format(h = 'baskerball',n = 'Peter',s = 'man')
  4. #输出结果:
  5. #name:Peter,sex:man,hobbie:basketball
  6. #name:Peter,sex:man,hobbie:basketball,name:Peter
  7. #name:Peter,sex:man.hobbie:baskerball,name:Peter
  1. def capitalize(self): # real signature unknown; restored from __doc__
  2. """
  3. S.capitalize() -> str
  4.  
  5. Return a capitalized version of S, i.e. make the first character
  6. have upper case and the rest lower case.
  7. """
  8. return ""
  9.  
  10. def casefold(self): # real signature unknown; restored from __doc__
  11. """
  12. S.casefold() -> str
  13.  
  14. Return a version of S suitable for caseless comparisons.
  15. """
  16. return ""
  17.  
  18. def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
  19. """
  20. S.center(width[, fillchar]) -> str
  21.  
  22. Return S centered in a string of length width. Padding is
  23. done using the specified fill character (default is a space)
  24. """
  25. return ""
  26.  
  27. def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  28. """
  29. S.count(sub[, start[, end]]) -> int
  30.  
  31. Return the number of non-overlapping occurrences of substring sub in
  32. string S[start:end]. Optional arguments start and end are
  33. interpreted as in slice notation.
  34. """
  35. return 0
  36.  
  37. def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
  38. """
  39. S.encode(encoding='utf-8', errors='strict') -> bytes
  40.  
  41. Encode S using the codec registered for encoding. Default encoding
  42. is 'utf-8'. errors may be given to set a different error
  43. handling scheme. Default is 'strict' meaning that encoding errors raise
  44. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  45. 'xmlcharrefreplace' as well as any other name registered with
  46. codecs.register_error that can handle UnicodeEncodeErrors.
  47. """
  48. return b""
  49.  
  50. def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
  51. """
  52. S.endswith(suffix[, start[, end]]) -> bool
  53.  
  54. Return True if S ends with the specified suffix, False otherwise.
  55. With optional start, test S beginning at that position.
  56. With optional end, stop comparing S at that position.
  57. suffix can also be a tuple of strings to try.
  58. """
  59. return False
  60.  
  61. def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
  62. """
  63. S.expandtabs(tabsize=8) -> str
  64.  
  65. Return a copy of S where all tab characters are expanded using spaces.
  66. If tabsize is not given, a tab size of 8 characters is assumed.
  67. """
  68. return ""
  69.  
  70. def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  71. """
  72. S.find(sub[, start[, end]]) -> int
  73.  
  74. Return the lowest index in S where substring sub is found,
  75. such that sub is contained within S[start:end]. Optional
  76. arguments start and end are interpreted as in slice notation.
  77.  
  78. Return -1 on failure.
  79. """
  80. return 0
  81.  
  82. def format(self, *args, **kwargs): # known special case of str.format
  83. """
  84. S.format(*args, **kwargs) -> str
  85.  
  86. Return a formatted version of S, using substitutions from args and kwargs.
  87. The substitutions are identified by braces ('{' and '}').
  88. """
  89. pass
  90.  
  91. def format_map(self, mapping): # real signature unknown; restored from __doc__
  92. """
  93. S.format_map(mapping) -> str
  94.  
  95. Return a formatted version of S, using substitutions from mapping.
  96. The substitutions are identified by braces ('{' and '}').
  97. """
  98. return ""
  99.  
  100. def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  101. """
  102. S.index(sub[, start[, end]]) -> int
  103.  
  104. Return the lowest index in S where substring sub is found,
  105. such that sub is contained within S[start:end]. Optional
  106. arguments start and end are interpreted as in slice notation.
  107.  
  108. Raises ValueError when the substring is not found.
  109. """
  110. return 0
  111.  
  112. def isalnum(self): # real signature unknown; restored from __doc__
  113. """
  114. S.isalnum() -> bool
  115.  
  116. Return True if all characters in S are alphanumeric
  117. and there is at least one character in S, False otherwise.
  118. """
  119. return False
  120.  
  121. def isalpha(self): # real signature unknown; restored from __doc__
  122. """
  123. S.isalpha() -> bool
  124.  
  125. Return True if all characters in S are alphabetic
  126. and there is at least one character in S, False otherwise.
  127. """
  128. return False
  129.  
  130. def isdecimal(self): # real signature unknown; restored from __doc__
  131. """
  132. S.isdecimal() -> bool
  133.  
  134. Return True if there are only decimal characters in S,
  135. False otherwise.
  136. """
  137. return False
  138.  
  139. def isdigit(self): # real signature unknown; restored from __doc__
  140. """
  141. S.isdigit() -> bool
  142.  
  143. Return True if all characters in S are digits
  144. and there is at least one character in S, False otherwise.
  145. """
  146. return False
  147.  
  148. def isidentifier(self): # real signature unknown; restored from __doc__
  149. """
  150. S.isidentifier() -> bool
  151.  
  152. Return True if S is a valid identifier according
  153. to the language definition.
  154.  
  155. Use keyword.iskeyword() to test for reserved identifiers
  156. such as "def" and "class".
  157. """
  158. return False
  159.  
  160. def islower(self): # real signature unknown; restored from __doc__
  161. """
  162. S.islower() -> bool
  163.  
  164. Return True if all cased characters in S are lowercase and there is
  165. at least one cased character in S, False otherwise.
  166. """
  167. return False
  168.  
  169. def isnumeric(self): # real signature unknown; restored from __doc__
  170. """
  171. S.isnumeric() -> bool
  172.  
  173. Return True if there are only numeric characters in S,
  174. False otherwise.
  175. """
  176. return False
  177.  
  178. def isprintable(self): # real signature unknown; restored from __doc__
  179. """
  180. S.isprintable() -> bool
  181.  
  182. Return True if all characters in S are considered
  183. printable in repr() or S is empty, False otherwise.
  184. """
  185. return False
  186.  
  187. def isspace(self): # real signature unknown; restored from __doc__
  188. """
  189. S.isspace() -> bool
  190.  
  191. Return True if all characters in S are whitespace
  192. and there is at least one character in S, False otherwise.
  193. """
  194. return False
  195.  
  196. def istitle(self): # real signature unknown; restored from __doc__
  197. """
  198. S.istitle() -> bool
  199.  
  200. Return True if S is a titlecased string and there is at least one
  201. character in S, i.e. upper- and titlecase characters may only
  202. follow uncased characters and lowercase characters only cased ones.
  203. Return False otherwise.
  204. """
  205. return False
  206.  
  207. def isupper(self): # real signature unknown; restored from __doc__
  208. """
  209. S.isupper() -> bool
  210.  
  211. Return True if all cased characters in S are uppercase and there is
  212. at least one cased character in S, False otherwise.
  213. """
  214. return False
  215.  
  216. def join(self, iterable): # real signature unknown; restored from __doc__
  217. """
  218. S.join(iterable) -> str
  219.  
  220. Return a string which is the concatenation of the strings in the
  221. iterable. The separator between elements is S.
  222. """
  223. return ""
  224.  
  225. def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  226. """
  227. S.ljust(width[, fillchar]) -> str
  228.  
  229. Return S left-justified in a Unicode string of length width. Padding is
  230. done using the specified fill character (default is a space).
  231. """
  232. return ""
  233.  
  234. def lower(self): # real signature unknown; restored from __doc__
  235. """
  236. S.lower() -> str
  237.  
  238. Return a copy of the string S converted to lowercase.
  239. """
  240. return ""
  241.  
  242. def lstrip(self, chars=None): # real signature unknown; restored from __doc__
  243. """
  244. S.lstrip([chars]) -> str
  245.  
  246. Return a copy of the string S with leading whitespace removed.
  247. If chars is given and not None, remove characters in chars instead.
  248. """
  249. return ""
  250.  
  251. def maketrans(self, *args, **kwargs): # real signature unknown
  252. """
  253. Return a translation table usable for str.translate().
  254.  
  255. If there is only one argument, it must be a dictionary mapping Unicode
  256. ordinals (integers) or characters to Unicode ordinals, strings or None.
  257. Character keys will be then converted to ordinals.
  258. If there are two arguments, they must be strings of equal length, and
  259. in the resulting dictionary, each character in x will be mapped to the
  260. character at the same position in y. If there is a third argument, it
  261. must be a string, whose characters will be mapped to None in the result.
  262. """
  263. pass
  264.  
  265. def partition(self, sep): # real signature unknown; restored from __doc__
  266. """
  267. S.partition(sep) -> (head, sep, tail)
  268.  
  269. Search for the separator sep in S, and return the part before it,
  270. the separator itself, and the part after it. If the separator is not
  271. found, return S and two empty strings.
  272. """
  273. pass
  274.  
  275. def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
  276. """
  277. S.replace(old, new[, count]) -> str
  278.  
  279. Return a copy of S with all occurrences of substring
  280. old replaced by new. If the optional argument count is
  281. given, only the first count occurrences are replaced.
  282. """
  283. return ""
  284.  
  285. def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  286. """
  287. S.rfind(sub[, start[, end]]) -> int
  288.  
  289. Return the highest index in S where substring sub is found,
  290. such that sub is contained within S[start:end]. Optional
  291. arguments start and end are interpreted as in slice notation.
  292.  
  293. Return -1 on failure.
  294. """
  295. return 0
  296.  
  297. def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  298. """
  299. S.rindex(sub[, start[, end]]) -> int
  300.  
  301. Return the highest index in S where substring sub is found,
  302. such that sub is contained within S[start:end]. Optional
  303. arguments start and end are interpreted as in slice notation.
  304.  
  305. Raises ValueError when the substring is not found.
  306. """
  307. return 0
  308.  
  309. def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  310. """
  311. S.rjust(width[, fillchar]) -> str
  312.  
  313. Return S right-justified in a string of length width. Padding is
  314. done using the specified fill character (default is a space).
  315. """
  316. return ""
  317.  
  318. def rpartition(self, sep): # real signature unknown; restored from __doc__
  319. """
  320. S.rpartition(sep) -> (head, sep, tail)
  321.  
  322. Search for the separator sep in S, starting at the end of S, and return
  323. the part before it, the separator itself, and the part after it. If the
  324. separator is not found, return two empty strings and S.
  325. """
  326. pass
  327.  
  328. def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  329. """
  330. S.rsplit(sep=None, maxsplit=-1) -> list of strings
  331.  
  332. Return a list of the words in S, using sep as the
  333. delimiter string, starting at the end of the string and
  334. working to the front. If maxsplit is given, at most maxsplit
  335. splits are done. If sep is not specified, any whitespace string
  336. is a separator.
  337. """
  338. return []
  339.  
  340. def rstrip(self, chars=None): # real signature unknown; restored from __doc__
  341. """
  342. S.rstrip([chars]) -> str
  343.  
  344. Return a copy of the string S with trailing whitespace removed.
  345. If chars is given and not None, remove characters in chars instead.
  346. """
  347. return ""
  348.  
  349. def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  350. """
  351. S.split(sep=None, maxsplit=-1) -> list of strings
  352.  
  353. Return a list of the words in S, using sep as the
  354. delimiter string. If maxsplit is given, at most maxsplit
  355. splits are done. If sep is not specified or is None, any
  356. whitespace string is a separator and empty strings are
  357. removed from the result.
  358. """
  359. return []
  360.  
  361. def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
  362. """
  363. S.splitlines([keepends]) -> list of strings
  364.  
  365. Return a list of the lines in S, breaking at line boundaries.
  366. Line breaks are not included in the resulting list unless keepends
  367. is given and true.
  368. """
  369. return []
  370.  
  371. def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
  372. """
  373. S.startswith(prefix[, start[, end]]) -> bool
  374.  
  375. Return True if S starts with the specified prefix, False otherwise.
  376. With optional start, test S beginning at that position.
  377. With optional end, stop comparing S at that position.
  378. prefix can also be a tuple of strings to try.
  379. """
  380. return False
  381.  
  382. def strip(self, chars=None): # real signature unknown; restored from __doc__
  383. """
  384. S.strip([chars]) -> str
  385.  
  386. Return a copy of the string S with leading and trailing
  387. whitespace removed.
  388. If chars is given and not None, remove characters in chars instead.
  389. """
  390. return ""
  391.  
  392. def swapcase(self): # real signature unknown; restored from __doc__
  393. """
  394. S.swapcase() -> str
  395.  
  396. Return a copy of S with uppercase characters converted to lowercase
  397. and vice versa.
  398. """
  399. return ""
  400.  
  401. def title(self): # real signature unknown; restored from __doc__
  402. """
  403. S.title() -> str
  404.  
  405. Return a titlecased version of S, i.e. words start with title case
  406. characters, all remaining cased characters have lower case.
  407. """
  408. return ""
  409.  
  410. def translate(self, table): # real signature unknown; restored from __doc__
  411. """
  412. S.translate(table) -> str
  413.  
  414. Return a copy of the string S in which each character has been mapped
  415. through the given translation table. The table must implement
  416. lookup/indexing via __getitem__, for instance a dictionary or list,
  417. mapping Unicode ordinals to Unicode ordinals, strings, or None. If
  418. this operation raises LookupError, the character is left untouched.
  419. Characters mapped to None are deleted.
  420. """
  421. return ""
  422.  
  423. def upper(self): # real signature unknown; restored from __doc__
  424. """
  425. S.upper() -> str
  426.  
  427. Return a copy of S converted to uppercase.
  428. """
  429. return ""
  430.  
  431. def zfill(self, width): # real signature unknown; restored from __doc__
  432. """
  433. S.zfill(width) -> str
  434.  
  435. Pad a numeric string S with zeros on the left, to fill a field
  436. of the specified width. The string S is never truncated.
  437. """
  438. return ""

str的方法集合

四、列表(list):对列表进行增删改,会改变原列表

  1、增:3种方式:.append(元素),元素可以为数字、布尔值、字符串、列表、元组、字典,在列表末端加入元素

           .insert(位置,元素),元素可以为数字、布尔值、字符串、列表、元组、字典,在指定位置加入元素

             .extend(元素),元素为可迭代对象,可以为数字、布尔值、字符串、列表、元组、字典,在列表末端依次加入

  1. li = [1,2,'a',True,('b',3,5)]
  2. li.append('abc')
  3. print(li)
  4. #输出结果:[1, 2, 'a', True, ('b', 3, 5), 'abc']
  5.  
  6. li = [1,2,'a',True,('b',3,5)]
  7. li.insert(1,'你好')
  8. print(li)
  9. #输出结果:[1, '你好', 2, 'a', True, ('b', 3, 5)]
  10.  
  11. li = [1,2,'a',True,('b',3,5)]
  12. li.extend('aoe')
  13. print(li)
  14. #输出结果:[1, 2, 'a', True, ('b', 3, 5), 'a', 'o', 'e']

  2、删:4种方法:.pop(元素位置),pop删除会生成一个结果,结果为删除的元素

           .remove('元素'),不会生成结果, 有多个相同的元素,只会删除第一个匹配的元素

           .clear(),情况列表所有数据,变成空列表

           del li[起始位置:结束位置:步长],步长可以为空,默认为1,del li 直接把列表删除

  1. li = [1,2,'a',True,('b',3,5)]
  2. a = li.pop(1)
  3. print(a)
  4. print(li)
  5. #输出结果:
  6. #
  7. #[1, 'a', True, ('b', 3, 5)]
  8.  
  9. li = [1,2,'a',True,('b',3,5)]
  10. li.remove(1)
  11. print(li)
  12. #输出结果:[2, 'a', True, ('b', 3, 5)]
  13.  
  14. li = [1,2,'a',True,('b',3,5)]
  15. li.clear()
  16. print(li)
  17. #输出结果:[]
  18.  
  19. li = [1,2,'a',True,('b',3,5)]
  20. del li[0:3:2]
  21. print(li)
  22. #输出结果:[2,True,('b',3,5)]

  

  3、改:li[元素下标] = 新元素,新元素可以为数字、布尔值、字符串、列表、元组、字典

       li[起始位置:结束位置,新元素],首先会把起始位置到结束位置的元素删除,然后迭代地增加新元素

  1. li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d']
  2. li[2] = 'ap'
  3. print(li)
  4. #输出结果:[1, 3, 'ap', '你', True, (1, 2, 'w'), [3, 9, 'l'], 'd']
  5.  
  6. li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d']
  7. li[1:3] = 'oip'
  8. print(li)
  9. #输出结果:[1, 'o', 'i', 'p', '你', True, (1, 2, 'w'), [3, 9, 'l'], 'd']

  4、查:按索引查:li[元素位置];按切片查:li[起始位置:结束位置:步长];li.index(元素,起始位置,结束位置),通过元素找索引,起始位置、结束位置可以不填,默认为整个列表

  1. li = [1,3,'a','你',True,(1,2,'w'),[3,9,'l'],'d']
  2. print(li[-1])
  3. print(li[6:1:-2])
  4. #输出结果:
  5. #d
  6. #[[3, 9, 'l'], True, 'a']
  1. li = [1,3,'a',('c','d',7),'fd']
  2. print(li.index(3))
  3. #输出结果:1

  5、排序:正序:li.sort(),数字由小到大排序,字母则按ascii码排序;反转:li.reverse(),将列表的元素倒过来排序

  1. li = [1,3,6,2,9,8,4,7,5,0]
  2. li.sort()
  3. print(li)
  4. #输出结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  5.  
  6. li = [1,3,6,2,9,8,4,7,5,0]
  7. li.reverse()
  8. print(li)
  9. #输出结果:[0, 5, 7, 4, 8, 9, 2, 6, 3, 1]
  10.  
  11. li = [1,3,6,2,9,8,4,7,5,0]
  12. li.sort(reverse = True)
  13. print(li)
  14. #输出结果:[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

  6、计算元素出现次数:a.count(元素),字符串的count可以切片,列表的count不可以切片

  1. a = [1,2,3,4,5]
  2. print(a.count(2))
  3. #输出结果:1
  1. def append(self, p_object): # real signature unknown; restored from __doc__
  2. """ L.append(object) -> None -- append object to end """
  3. pass
  4.  
  5. def clear(self): # real signature unknown; restored from __doc__
  6. """ L.clear() -> None -- remove all items from L """
  7. pass
  8.  
  9. def copy(self): # real signature unknown; restored from __doc__
  10. """ L.copy() -> list -- a shallow copy of L """
  11. return []
  12.  
  13. def count(self, value): # real signature unknown; restored from __doc__
  14. """ L.count(value) -> integer -- return number of occurrences of value """
  15. return 0
  16.  
  17. def extend(self, iterable): # real signature unknown; restored from __doc__
  18. """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
  19. pass
  20.  
  21. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  22. """
  23. L.index(value, [start, [stop]]) -> integer -- return first index of value.
  24. Raises ValueError if the value is not present.
  25. """
  26. return 0
  27.  
  28. def insert(self, index, p_object): # real signature unknown; restored from __doc__
  29. """ L.insert(index, object) -- insert object before index """
  30. pass
  31.  
  32. def pop(self, index=None): # real signature unknown; restored from __doc__
  33. """
  34. L.pop([index]) -> item -- remove and return item at index (default last).
  35. Raises IndexError if list is empty or index is out of range.
  36. """
  37. pass
  38.  
  39. def remove(self, value): # real signature unknown; restored from __doc__
  40. """
  41. L.remove(value) -> None -- remove first occurrence of value.
  42. Raises ValueError if the value is not present.
  43. """
  44. pass
  45.  
  46. def reverse(self): # real signature unknown; restored from __doc__
  47. """ L.reverse() -- reverse *IN PLACE* """
  48. pass
  49.  
  50. def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
  51. """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
  52. pass

列表的方法集合

五、for循环:for i in 可迭代对象:,字符串、列表、元组、字典、range()都为可迭代对象

  1. for i in 'asda':
  2. print(i)
  3. #输出结果:
  4. #a
  5. #s
  6. #d
  7. #a
  8.  
  9. for i in range(1,5):
  10. print(i)
  11. #输出结果
  12. #
  13. #
  14. #
  15. #

六、元组(tuple):元组的元素不能修改,但是元素里面的元素可以修改

  1. def count(self, value): # real signature unknown; restored from __doc__
  2. """ T.count(value) -> integer -- return number of occurrences of value """
  3. return 0
  4.  
  5. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  6. """
  7. T.index(value, [start, [stop]]) -> integer -- return first index of value.
  8. Raises ValueError if the value is not present.
  9. """
  10. return 0

元组的方法集合

七、字典(dic):无序、以键值对形式存在、是python唯一具有映射关系的数据类型

  字典的键必须是可哈希(不可变的数据类型)的,而且键必须唯一

  不可变的数据类型:数字、布尔值、字符串、元组;可变的数据类型:列表、字典、集合(set)

  1、增:方法一:dic['abc'] = '123',字典里没有的键会增加,字典里有的键则会把值覆盖

       方法二:dic.setdefault(键,值),字典里没有的键会增加,字典里已有的键的值不会变,值可以不填,默认为None

  1. dic = {'name':'abc','age':18}
  2. dic['sex'] = 'man'
  3. print(dic)
  4. dic['name'] = 'qwe'
  5. print(dic)
  6. #输出结果:
  7. #{'name': 'abc', 'age': 18, 'sex': 'man'}
  8. #{'name': 'qwe', 'age': 18, 'sex': 'man'}
  9.  
  10. dic = {'name':'abc','age':18}
  11. dic.setdefault('sex','man')
  12. print(dic)
  13. dic.setdefault('name','qwe')
  14. print(dic)
  15. #输出结果:
  16. #{'name': 'abc', 'age': 18, 'sex': 'man'}
  17. #{'name': 'abc', 'age': 18, 'sex': 'man'}

  2、删:dic.pop(键),删除一个键值对,返回删除键对应的值,如果键不存在,则会报错,此时可以在写成dic.pop(键,内容),如果键不存在,则会返回内容,不会报错

       dic.popitem(),随机删除一个键值对,将删除的键值以元组的形式 返回

       dic.clear(),清空字典,返回值为None;del dic,删除整个字典

       del dic[键],删除字典的一个键值对,没有返回值,如果键不存在,报错

  1. dic = {'name':'abc','age':18}
  2. print(dic.pop('name')) #abc
  3. print(dic) #{'age':18}
  4. print(dic.pop('asd','mmm')) #mmm
  5. print(dic) #{'age':18}
  6.  
  7. dic = {'name':'abc','age':18}
  8. print(dic.popitem()) #('age':18)
  9. print(dic) #{'name':'abc'}
  10.  
  11. dic = {'name':'abc','age':18}
  12. print(dic.clear()) #None
  13. print(dic) #{}
  14.  
  15. dic = {'name':'abc','age':18}
  16. del dic['name']
  17. print(dic) #{'age': 18}

  3、改:dic[键] = 值,如果键存在,则改值,如果键没有,则新增键值对

       dic1 = {},dic2 = {},dic1.update(dic2),将dic2的内容更新到dic1,即将dic2的键值对新增并覆盖到dic1

  1. dic = {'name':'abc','age':18,'job':'teacher'}
  2. dic['name'] = '天空'
  3. print(dic) #{'name': '天空', 'age': 18, 'job': 'teacher'}
  4.  
  5. dic1 = {'name':'A','age':18,'sex':'man'}
  6. dic2 = {'name':'B','hobbie':'swim'}
  7. dic1.update(dic2)
  8. print(dic1) #{'name': 'B', 'age': 18, 'sex': 'man', 'hobbie': 'swim'}

  4、查:dic[键],如果键没有,报错

       dic.get(键,内容),如果键存在,返回键对应的值,如果键存在返回内容,内容可以不填,如果键不存在,则返回None

  1. dic = {'name':'abc','age':18,'job':'teacher'}
  2. print(dic['name']) #abc
  3. print(dic.get('namea')) #None
  4. print(dic.get('namea','没有')) #没有

  5、其它操作:dic.items(),返回值是一个列表,这个列表由元组组成,元组为dic的键值对

          dic.keys(),返回值是一个列表,列表由dic的键组成

          dic,values(),返回值是一个列表,列表由dic的值组成

  1. dic = {'a':1,'b':2,'c':3,'d':4}
  2. print(dic.keys()) #dict_keys(['a', 'b', 'c', 'd'])
  3. print(dic.values()) #dict_values([1, 2, 3, 4])
  4. print(dic.items()) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

  6、字典的循环:for i in dic.keys(),返回键;

           for i in dic.values(),返回值;

           for i in dic.items(),返回键值对的元组;

           for i,j in dic.items(),返回键、值;

           for i in dic,返回键;

  1. dic = {"name":"guku","age":18,"sex":"male"}
  2. for i in dic.keys():
  3. print(i)
  4. #name
  5. #age
  6. #sex
  7.  
  8. for i in dic.values():
  9. print(i)
  10. #guku
  11. #
  12. #male
  13.  
  14. for i in dic.items():
  15. print(i)
  16. #('name', 'guku')
  17. #('age', 18)
  18. #('sex', 'male')
  19.  
  20. for i,j in dic.items():
  21. print(i,j)
  22. #name guku
  23. #age 18
  24. #sex male
  25.  
  26. for i in dic:
  27. print(i)
  28. #name
  29. #age
  30. #sex
  1. def clear(self): # real signature unknown; restored from __doc__
  2. """ D.clear() -> None. Remove all items from D. """
  3. pass
  4.  
  5. def copy(self): # real signature unknown; restored from __doc__
  6. """ D.copy() -> a shallow copy of D """
  7. pass
  8.  
  9. @staticmethod # known case
  10. def fromkeys(*args, **kwargs): # real signature unknown
  11. """ Returns a new dict with keys from iterable and values equal to value. """
  12. pass
  13.  
  14. def get(self, k, d=None): # real signature unknown; restored from __doc__
  15. """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
  16. pass
  17.  
  18. def items(self): # real signature unknown; restored from __doc__
  19. """ D.items() -> a set-like object providing a view on D's items """
  20. pass
  21.  
  22. def keys(self): # real signature unknown; restored from __doc__
  23. """ D.keys() -> a set-like object providing a view on D's keys """
  24. pass
  25.  
  26. def pop(self, k, d=None): # real signature unknown; restored from __doc__
  27. """
  28. D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  29. If key is not found, d is returned if given, otherwise KeyError is raised
  30. """
  31. pass
  32.  
  33. def popitem(self): # real signature unknown; restored from __doc__
  34. """
  35. D.popitem() -> (k, v), remove and return some (key, value) pair as a
  36. 2-tuple; but raise KeyError if D is empty.
  37. """
  38. pass
  39.  
  40. def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
  41. """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
  42. pass
  43.  
  44. def update(self, E=None, **F): # known special case of dict.update
  45. """
  46. D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
  47. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
  48. If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
  49. In either case, this is followed by: for k in F: D[k] = F[k]
  50. """
  51. pass
  52.  
  53. def values(self): # real signature unknown; restored from __doc__
  54. """ D.values() -> an object providing a view on D's values """
  55. pass

字典的方法集合

Python学习(三) —— 基本数据类型的更多相关文章

  1. Python学习笔记 - day3 - 数据类型及运算符

    Python的数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同 ...

  2. 记录我的 python 学习历程-Day03 数据类型 str切片 for循环

    一.啥是数据类型 ​ 我们人类可以很容易的分清数字与字符的区别,但是计算机并不能呀,计算机虽然很强大,但从某种角度上看又很傻,除非你明确的告诉它,1是数字,"汉"是文字,否则它是分 ...

  3. python学习第九天数据类型列表创建,查找操作方法

    数据类型中列表是整个python最常用的数据类型,列表最常用的方法就是创建,增删改查,切片,循环以及排序等系列操作,任何操作都离不开增删改查操作,这样很容记住操作方法 1,列表的创建 list=[] ...

  4. Python学习手册之数据类型

    在上一篇文章中,我们介绍了 Python 的异常和文件,现在我们介绍 Python 中的数据类型. 查看上一篇文章请点击:https://www.cnblogs.com/dustman/p/99799 ...

  5. Python学习-字符编码, 数据类型

    本篇主要内容: 字符编码 Python中的数据类型有哪些 类型的一些常用操作及方法 一.字符编码 编码解释的大部分内容摘自廖雪峰老师教程中的讲解,点击跳转. 简单介绍: 我们知道计算机只能处理数字,如 ...

  6. python学习之核心数据类型

    python核心数据类型 对象类型 例子 数字 1234,-345 字符串 'spam' 列表 [1,3,'ds'] 元组 (1,'spam',6) 字典 {'name':'lili','age':1 ...

  7. python学习03-数据类型

    一.基本数据类型--数字 布尔型 bool型只有两个值:True和False 之所以将bool值归类为数字,是因为我们也习惯用1表示True,0表示False. 以下是布尔值是False的各种情况: ...

  8. python学习之基本数据类型

    python的基本数据类型有数字.字符串.列表.字典.元祖.布尔值 一.数字 1.1.字符转换为数字 实例: a=" b=int(a) print(b+) 运行结果: 可以用type查看数据 ...

  9. Python学习笔记3_数据类型

    Python数据类型:数字.字符串.列表.元祖.字典 一.数字类型:(整型.长整型.浮点型.复数型) 1.整型(int):表示范围-2,147,483,648到2,147,483,647 2.长整型( ...

  10. 02 Python学习笔记-基本数据类型(二)

    一.基本知识 1.缩进: 2.一行多条语句: 3.断行: 4.注释 # 单行注释 '''这是一段 多行注释''' 5. 变量 1. 变量类型(局部变量.全局变量.系统变量) 2. 变量赋值 多重赋值x ...

随机推荐

  1. 抢红包时用到的redis函数

    2018-2-8 10:25:11 星期四 抢红包时经常会用redis(等其他nosql)的原子性函数去限流, 防止抢超, 下边列出一些主要的原子性函数 限制每个人只能抢一次 getSet(): 设置 ...

  2. 用Go的风格实现素数筛选

    package main import ( "fmt" "time" ) func source(ch chan<- int) { ; i < En ...

  3. 通信——基于Xmpp协议实现的聊天室

    前段时间写了个自定义通信协议的聊天室(即用\r\n标记字符串,作为一句话),总感觉自己弄的那个协议实现虽然简单,但是拓展性就太差了,只适合于发送聊天的内容,难以包含更多的信息.基于上述几点,于是就开始 ...

  4. C/C++中如何在main()函数之前执行一条语句?

    在C语言中,如果使用GCC的话,可以通过attribute关键字声明constructor和destructor(C语言中如何在main函数开始前执行函数) #include <stdio.h& ...

  5. 【原创】大叔经验分享(32)docker挂载文件修改生效

    docker经常需要挂载文件到容器中,比如启动nginx # docker run -d --name test_nginx -v /tmp/nginx.conf:/etc/nginx/nginx.c ...

  6. Django 笔记(六)mysql增删改查

    注:增删改查表数据在 views.py 内 添加表数据: 删表数据:  改表数据:  查表数据: 常用的查询方法: 常用的查询条件: 相当于SQL语句中的where语句后面的条件 语法:字段名__规则

  7. html5中如何去掉input type date默认

    html5中如何去掉input type date默认样式 2.对日期时间控件的样式进行修改目前WebKit下有如下9个伪元素可以改变日期控件的UI:::-webkit-datetime-edit – ...

  8. JNI 开发基础篇:Android开发中os文件的探索

    正题: android开发中,时长会遇到os文件的使用,那么os文件到底是什么?在这篇文章中会进行说明. .os文件在android中意味着C语言书写的方法,经android提供的ndk进行编译,从而 ...

  9. python 与mongodb 交互

    创建管理员 1 > use admin 2 switched to db admin 3 > db 4 admin 5 > db.createUser({user:'admin',p ...

  10. LeetCode(91):解码方法

    Medium! 题目描述: 一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计 ...