A list of basic Python knowledge, Ganso, dictionaries, collections, strings.

Source: Internet
Author: User
Tags shallow copy

1. List of mutable types

The list is defined by [] to be variable, can be queried by the index value of the field can be appended, deleted, etc.

"' Python
Names= ' Zhangyang Guyun xiangpeng Xuliangwei '
names = [' Zhang ', ' Zhuang ', ' Chen ', ' Qiang ']
Name_list = [[' Zhang ', ' Zhuang '], [' Chen ', ' Qiang ']
List_num = [1, 4, 5, 2, 3, 4, 52, 54]
Print (len (names)) # Get list length

Print ("Aaffaa". Count ("a")) # Gets the number of occurrences of a string

Print (Names[1:3]) # Slice

Print (names[-1]) # gets the last element
Print (names[-2:]) #
Names.append (' Qianqq ') # Append

Names.insert (1, ' Chengrouhua ') # Insertion
Names.insert (3, "Xinzhiyu")
NAMES[2] = "IXNIXN" # Modify
Names.remove ("Qiang")
Del Names[0]
Names.pop (0) # Removes the element and returns the value of the deleted element can be indexed delete the value of the pointing without adding the last
del Names[2:4] # slice Delete

Names.sort () # Sort the original list with a return value (elements are numbers, characters, etc., the elements inside must be the same)
Print (sorted (list_num, reverse=true)) # This has a return value does not change the value of the original list key corresponding collation
Print (List_num)

For I in Names:
Print (i) # Loop through the list

For I in range (1, 10, 2):
Print (i)

Print (Names[::2]) # interlaced filtering

Print (' Zhuang ' in Names) # Determine if the field is in the list

name1 = ["Wutenglan", "Sanglaoshi"]
name2 = ["Bojie", "Xize"]

Name = Name1.extend (name2) # will name2 and go to name1

Names2 = Names.copy () # Shallow copy

Print (dir (names) #) # Gets the methods supported by the list

```
2. Immutable type elements

Ganso, is a kind of not become a list form, once the definition can not be changed, generally used for database connection, binding IP and port use.

元祖特性:1.不可变,定义元祖 的时候如果只有一个元素这样必须在元祖后面加逗号加以区分。注:元祖内部如果有列表等可变元素则可以修改2.只有查询功能。通过索引值查询内部数据

3. Variable Type dictionary

The dictionary has the following characteristics:

1.key-value格式,key是唯一的2.无序的3.查询速度快

"' Python

info={
' stu1101 ': "Wu Teng Lang",
' stu1102 ': "Cang",
' stu1103 ': "Xiaoze",
' stu1104 ': "Bo Jie"
}
B={1:2,3:4}

Print (info[' stu1101 ') #查看字典stu1101 the key corresponding to the value

info[' stu1101 ']= ' mmmmm ' #如果字典有这个key值则修改, no add
info[' stu1105 ']= ' sssss '

Info.setdefault (' stu1101 ', ' alxe ') #如果key的值 modified in the dictionary, no added

Info.update (b) # Appends the field of the B dictionary to the info dictionary, if repeated updates are followed by fields.

Info.pop (' stu1105 ') #通过key的值来删除字典的对应的值 the Pop method has a return value, return the value of the deleted element value does not exist key is an error Dic.pop (Key[,default]) can specify the value There is no value with Defalut

Print (Info.get (' stu1106 ')) # This is a way to get something worthwhile by key so it won't be an error, no then return

Print (' stu1104 ' in info) #判断key的值在不在字典中 judged by the value of key.

Print (Info.keys ()) #返回所有的key #打印所有字典key的 value
Print (Info.values ()) #返回字典所有的value值
Print (Info.items ()) # Return to the progenitor to make a key and value into a meta-ancestor
Info_list = List (Info.items ()) # Changes the value of the dictionary key to a list store

For k in info:# K is the value of info key traversal dictionary key print
Print (K,info[k])
```
4. Mutable type Collection

Set: The whole of one or more elements is called a set.
features of the collection :

1.天然去重 2.集合内部元素是无序的3.通过运算可以取出两个集合的符合条件的元素类型组成一个新的集合

The common set operations are as follows:

B={1,2,3,4,5,5,5,6}#互异性天然去重的原则C={2,3,4,8,9,Ten, About, $}s_set= Set("Hello")# {' L ', ' h ', ' e ', ' o '} No need and go heavy#集合的常用操作S_set={' A ',' B ',' C '}s_set.add ("D")# Add to Collection# Increase of the sequence:Update (), and update is similar to the Extend method, the Update method can support the simultaneous passing of multiple parameter a={1,2}a.update ([3,4],[1,2,7]) A={1,2,3,4,7}a.update ("Hello") A={1,2,3,4,7,' h ',' E ',' l ',' O '}#对集合元素的单个删除#集合删除有两个办法:#元素不在原集合中时:# Set.discard (x) does not throw an exception# Set.remove (x) throws Keyerror errorA={1,2,3,4}a.discard (1) A={2,3,4}a.discard (1) A={2,3,4}a.remove (1) Traceback (most recent): File"<input>", line1,inch <Module>Keyerror:1B.add ( -)#增加元素B.remove ( -)#删除元素 Error if no elementB.discard (4)#删除元素 don't have an error .Print(b) B.pop ()#删除元素 (Any)Print(b)# Empty SetPop (): The result of a pop return cannot be determined because the collection is unordered. And calling pop when the collection is empty throws a keyerror error. Clear (): Empty collection# Collection OperationsPrint(b-C#意思就是拿b中的每一个元素去减c中的元素, get a different set. Print(b|C#并集两个集合的合并Print(b^C#两个集合中不是共同部分的元素取出来D=Set(info)#设置集合 Dictionary is the value of key

5. Manipulation of strings

Name=' aaalcx Lill 'Print(Name.index ("L"))Print(Name.count ("L"))# Statistics string number of a stringPrint(Name.capitalize ())#首字母大写Print(Name.center ( -,'*'))#把name放在中间 50 character (S )Print(Name.replace (' l ',' L ',4))#代替 of three parametersPrint("123". IsDigit ())#判断是否是整数Print("Aaaooolll". EndsWith (' ll ')) msg= ' My name is {} ' and ' is ' {} 'Print(Msg.partition (' is '))#is Middle Division Cheng YuanjuPrint(Msg.format("ZJ","very")) Name.join ("CX")Print(Name.join ("CXB"))# operate on numbersName=' ABCD Lill 'Name1="ABC\ tLill "Name.strip ()#变成字符串Name.title ()#变成标题Print(Name.rsplit ())Print(Name.capitalize ())#首字母大写Print(Name.count ("a"))# Statistical CharactersPrint(Name.center ( -,"*"))#一共 Print 50 characters not enough to fill in, put name in the middlePrint(Name.endswith ("LL"))# To determine the end of a stringPrint(Name1.expandtabs ( -))Print(Name.find ("Li"))# find an index! String can be slicedName3="My name is{Name} and age are{Age}"Print(Name3.format(Name="Alix", age="a"))Print(Name3.format_map ({"Name":"Alex","Age":"very"}))Print(Name3.index ("Y"))Print(Name.isalnum ())# is it Arabic?Print(Name.isalpha ())#判断纯粹的英文字符Print(Name.isdecimal ())#判断十进制Print(Name.isdigit ())# determine if integerPrint(Name.isidentifier ())#判断是不是合法的标识符 (variable name)Print(Name.islower ())# judgment is lowercase! Print(Name.isnumeric ())#判断是否是数字!! Only the number returns truePrint(Name.isspace ())Print(Name.istitle ())Print(Name.isprintable ())# is printable! Device terminal files in TTY filesPrint(Name.isupper ())# It's All caps #Print("*****")Print("|". Join (["1","2","3","4"]))# The string inside the list becomes a stringPrint("*****")Print(Name.ljust ( -,"-"))# Back up *Print(Name.rjust ( -,'-'))Print(Name.lower ())# Uppercase becomes lowercasePrint(Name.upper ())Print("\ nAlex\ n". Lstrip ())#左边去空格或者回车Print("\ nAlex\ n". Rstrip ())#右边边去空格或者回车Print(Name.strip ())#两边都去空格Print("Funny keys\ n") v=Str. Maketrans ("ABCdef","123456")# numbers correspond! Print("Alex Li". Translate (v))Print("Alex L". replace (' l ',' L ',1))Print("Alex Li". RFind ("L"))#找到最右边的的l and returnPrint(Name.split ())# photo Space is divided into listsPrint(Name.split (' A '))# Photo A is divided into listsPrint(Name.splitlines ())# Follow line break Linux windowPrint(Name.startswith (' A '))Print(Name.swapcase ())#大小写转换Print(Name.title ())# change TitlePrint("Alex Li". Zfill ( -))# 50 Not enough in front of 0Print("Name AAA". Split ()) name=' AA aaaa 'Print(Name.isalpha ())# Judging is not the alphabet! Print(Len(' Hello '. Encode ()))ImportString# Maketrans function corresponds to setting a format corresponding to Maketrans (Input,output) generated is a templateTable= Str. Maketrans (String.ascii_lowercase, string.ascii_lowercase[2:]+string.ascii_lowercase[0:2])#对应的方法为 TranslatePrint(Str. Translate (' AAA ', table))

A list of basic Python knowledge, Ganso, dictionaries, collections, strings.

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.