Learn the summary of Python lists, dictionaries, and collections

Source: Internet
Author: User
Tags printable characters
1. List

#!/usr/bin/env python#_*_coding:utf-8_*_names = [' Alex ', ' Tenglan ', ' Eric '] #print names[0]//python2.7 no brackets print ( Names[0])
#!/usr/bin/env python#_*_coding:utf-8_*_# slices: Take multiple elements names = ["Alex", "Tenglan", "Eric", "Rain", "Tom", "Amy"]print (names[ 1:4]) #追加names. Append ("Xiao") print (names) #插入names. Insert (2, "Force insert from Eric") print (names) #修改names [2]=] the substitution "print" ( Names
#删除del names[2]print (names) #删除指定元素names. Remove ("Eric") print (names) #删除列表最后一个值names. Pop () print (names)
#扩展b = [1,2,3]names.extend (b) print (names) #拷贝name_copy =names.copy () print (name_copy) #统计names =[' Alex ', ' Tenglan ', ' Amy ', ' Tom ', ' Amy ', 1, 2, 3]print (Names.count ("Amy")) #排序names [-3] = ' 1 ' names[-2] = ' 2 ' names[-1] = ' 3 ' Names.sort () print (NA Mes
#反转names. Reverse () print (names) #获取下标print (Names.index ("Amy"))

2, meta-group

Tuples are actually similar to the list, but also to save a group of numbers, it is not once created, it can not be modified, so it is called a read-only list

Grammar

Names = ("Alex", "Jack", "Eric")

It has only 2 methods, one is count, the other is index, complete.

#!/usr/bin/env python#_*_coding:utf-8_*_names = ("Alex", "Jack", "Eric") Print (Names.count ("Alex")) print (Names.index ("Jack"))

3. String manipulation

#检测字符串是否由字母和数字组成print (' 9aA '. Isalnum ()) #是否整数print (' 9 '. IsDigit ()) #检测字符串是否只由数字组成. This method is only for unicode objects str = u "this2009" Print (Str.isnumeric ()) str = u "23443434" Print (Str.isnumeric ()) #判断字符串所包含的字符是否全部可打印. The string contains non-printable characters, such as escape characters, that return Falseprint (Str.isprintable ()) #字符串是否仅包含空格或制表符. Note: The space character is different from the blank print (Str.isspace ())
#判断字符串每个单词的首字母是否大写print (Str.istitle ())
#判断所有字母字符是否全部大写print (Str.isupper ()) # ' Alex|jack|rain ' Print ("|". Join ([' Alex ', ' Jack ', ' Rain ']) #maketransintab = "Aeiou" Outtab = "12345" Trantab = Str.maketrans (intab, outtab) str = "This is String EXAMPLE....WOW!!! " Print (Str.translate (trantab)) #out: th3s 3s str3ng 2x1mpl2....w4w!!! Print (Msg.partition (' is ')) #out: (' My Name ', ' was ', ' {name}, and age ' {age} ') #替换print ("Alex Li, Chinese name is Lijie" . replace ("Li", "Li", 1))
#大小写互换str = "This is string EXAMPLE....WOW!!!" Print (Str.swapcase ()) print (Msg.zfill (+)) # Out:00000my name is {name}, and age is {Age}print (Msg.ljust (+, "-")) #my Nam E is {name}, and age was {age}-----Print (Msg.rjust (+, "-")) #-----My name is {name}, and ' age ' {age}# detects if a string can be used as a marker, that is, whether Conforming variable naming rules b= "ddefdsdff_ haha" print (B.isidentifier ())

4. Dictionary operation

Features of the dictionary:

Dict is disordered.

Key must be unique and so is inherently heavy

#!/usr/bin/env python#-*-coding:utf-8-*-# @Time    : 2017/3/26 13:26# @Author  : corasql# @Site    : # @File    : dic.py# @Software: pycharm Community editioninfo = {    ' stu1101 ': ' Tenglan Wu ',    ' stu1102 ': ' Longze luola ',    ' s tu1103 ': "Xiaoze Maliya",} #增加info ["stu1104"] = "Python" Print (info)
#修改info [' stu1101 '] = "Test" print (info) #删除info. Pop ("stu1101") #标准删除姿势print (info) del info[' stu1103 ']  # Change position Delete print (info) #随机删除info = {' stu1102 ': ' Longze luola ', ' stu1103 ': ' Xiaoze Maliya '}info.popitem () print (info) #查找info = {' stu1102 ': ' Longze luola ', ' stu1103 ': ' Xiaoze Maliya '}print ("stu1102" in Info) #标准用法print (info.get ("stu1102"))  # Get Print (info["stu1102"]) #同上, but see below
Print (info["stu1105"])  #如果一个key不存在, error, get no, not exist only return none# loop dict# method 1for key in info:    print (Key,info[key]) # Method 2for K,v in Info.items (): #会先把dict转成list, use    print (K,V) when the data is large

5. Set operation

A collection is an unordered, non-repeating combination of data, and its main functions are as follows:

Go to the weight, turn a list into a set, and then automatically go heavy.

Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set

s = set ([3,5,9,10])      #创建一个数值集合  t = set ("Hello")         #创建一个唯一字符的集合  A = T | s          # t and S of the set  B = t & s
  
   # T and s  C = t–s          # differential Set (item in T, but not in s)  d = t ^ s          # symmetric difference set (items in t or S, but not both)
  

Basic operation:

T.add (' x ')  # Add an item  s.update ([10,37,42])  # Add multiple items in S  use remove () to delete an item:  t.remove (' H ')
Len (s) sets  the length of  x in S to  test if X is a member of S X not in S to  test if X is not a member of S  s.issubset (t)  s <= t  Test if every element in S is in T  s.issuperset (t)  s >= T  Test if every element in T is in S  s.union (t)  s | t  return Back a new set contains each element in S and T  s.intersection (t)  S & T
Returns a new set containing the common elements in S and T  s.difference (t)  s-t  Returns a new set containing elements in s but not in T  s.symmetric_difference (t) 
  s ^ t  returns a new set containing non-repeating elements in S and T  s.copy ()  returns a shallow copy of set "s"

6. File operation

#!/usr/bin/env python#-*-coding:utf-8-*-# @Time    : 2017/3/26 14:00# @Author  : corasql# @Site    : # @File 
  : file.py# @Software: pycharm Community editionf = open (' lyrics ')  # opening file First_line = F.readline () print (' first line : ', First_line)  # read a line of print (' I am the divider '). Data = F.read ()  # Read All the rest of the content, do not use print (data) when the file is large  Print file F.close ()  # Close File

7, character encoding and transcoding

Need to know:

1. In Python2 the default encoding is ASCII, the default is Unicode in Python3

2.unicode is divided into utf-32 (4 bytes), utf-16 (accounting for two bytes), Utf-8 (1-4 bytes), so utf-16 is now the most commonly used Unicode version, but in the file is still utf-8, because the UTF8 save space

3. Encode in Py3, while transcoding will also change the string to bytes type, decode decoding will also turn bytes back to string

Python2#!/usr/bin/env python#-*-coding:utf-8-*-# @Time    : 2017/3/26 13:55# @Author  : corasql# @Site    : # @Fi Le    : decode2.py# @Software: Pycharm Community editionimport sysprint (sys.getdefaultencoding ())
msg = "I love Beijing Tian ' an gate" msg_gb2312 = Msg.decode ("Utf-8"). Encode ("gb2312") GB2312_TO_GBK = Msg_gb2312.decode ("GBK"). Encode ("GBK ") print (msg) print (msg_gb2312) print (GB2312_TO_GBK) python3#!/usr/bin/env python#-*-coding:utf-8-*-# @Time    : 2017/3/26 13:51# @Author  : corasql# @Site    : # @File    : decode.py# @Software: Pycharm Community editionimport Sy Sprint (Sys.getdefaultencoding ())
msg = "I love Beijing Tian ' an gate" #msg_gb2312 = Msg.decode ("Utf-8"). Encode ("gb2312") msg_gb2312 = Msg.encode ("gb2312") #默认就是unicode, no longer decode, the great ben Gb2312_to_unicode = Msg_gb2312.decode ("gb2312") Gb2312_to_utf8 = Msg _gb2312.decode ("gb2312"). Encode ("Utf-8") print (msg) print (msg_gb2312) print (gb2312_to_unicode) print (gb2312_to_ UTF8) 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.