Python base list, tuple, dictionary, collection usage

Source: Internet
Author: User

First, List

1. List definition

names=["Jhon", "Lucy", "Michel", "Tom", "Wiliam"]

List slices:

names=["Hexin", "Zhangliang", ["Caijie", "LiSi"], "Liyun", "Tianjun", ' Guyun ']print (names) print (Names[0]) print (names [1:3]) #不能取到索引为3的列表元素print (names[-1]) #取列表的倒数第一位的值print (names[-2:]) #取倒数两个值print (Names[0:3]) print (Names[:3]) # With print (Names[0:3]) equivalent print (Names.index ("Guyun"))  # printout index value print (Names[names.index ("Guyun")]) print ( Names.count ("Liyun"))  #打印输出列表中 number of "Liyun"

Results:

[' Hexin ', ' Zhangliang ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun '] hexin[' Zhangliang ', [' Caijie ', ' LiSi ']]liyun[' Guyun ', ' Liyun ' [' hexin ', ' Zhangliang ', [' Caijie ', ' LiSi ']][' hexin ', ' Zhangliang ', [' Caijie ', ' LiSi ']]5guyun2

2. Append and delete list elements

names=["Hexin", "Zhangliang", ["Caijie", "LiSi"], "Liyun", "Tianjun", ' Guyun ', "Liyun"]print (names) #列表追加: Names.append ("Reese") #默认插入到列尾
Names.insert (1, "Tangyu") #指定位置插入
Names[2]= "Xiao Jing" #指定位置插入
Print ("-----after append-----\ n", names) #列表删除: Names.remove ("Liyun") del Names[1] #删除列表中索引为1的值names. Pop () # Default Delete last value Names.pop (0) #删除第一个值print ("-----after delete-----\ n", names)

Operation Result:

[' Hexin ', ' Zhangliang ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun ']-----after append-----[' hexin ', ' Tangyu ', ' Xiao Jing ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun ', ' Reese ']-----after delete-----[' Xiao Jing ', [' Caijie ', ' LiSi '], ' Tia Njun ', ' Guyun ', ' Liyun ']

Delete entire list: del names

Reverse list value position: Name.reverse ()

Sort: Names.sort ()

3. List copy

Statement: Import Copy

List extension:

names=["Hexin", "Zhangliang", ["Caijie", "LiSi"], "Liyun", "Tianjun", ' Guyun ', "Liyun"]print (names) names2=[1,2,3,4] Names.extend (Names2) #将names2的值添加到names中print (names,names2)

Operation Result:

[' Hexin ', ' Zhangliang ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun '] [' Hexin ', ' Zhangliang ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun ', 1, 2, 3, 4] [1, 2, 3, 4]

List replication is slightly different from variable replication:

Copy of Import copy# variable: name1= "Lihai" name2=name1name1= "Tianjun" Print ("-----name1>>", name1) print ("-----name2> > ", name2) #列表的复制: names=[' 1 ', ' 2 ', ' 3 ']names2=names.copy () #浅copynames [0] = 55print ("-----names>> ", names) Print ("-----names2>>", Names2) names3=[1,2,[5,7],3]print ("-----Pre-Modified names3>>", Names3) names4=copy.copy (NAMES3) #浅copynames5 =copy.deepcopy (NAMES3) #深copynames3 [2][0]=66names3[0]=88print ("-----names3>>", Names3) Print ("-----names4>>", names4) print ("-----names5>>", names5)

Results:

-----name1>> Tianjun-----name2>> Lihai-----names>> [2 ', ' 3 ']-----names2>> [' 1 ', ' 2 ', ' 3 '] -----modified names3>> [1, 2, [5, 7], 3]-----names3>> [2, 7], [3], 1]-----names4>> [, 2, [, 7], 3]---- -names5>> [1, 2, [5, 7], 3]

The variable name2 will not change with the name1 after the assignment, the list mames5 under the deep copy condition, the result is the same as the copy effect of the variable, and does not change with the names3 change, and the list names4 through the shallow copy, The outermost layer does not change with names3 changes, but the inner layers change with names3.

4. Use the For loop to print the list names

names=["Hexin", "Zhangliang", ["Caijie", "LiSi"], "Liyun", "Tianjun", ' Guyun ', "Liyun"]for i in Names:    print (i)

Results:

hexinzhangliang[' Caijie ', ' LiSi ']liyuntianjunguyunliyun

5. Print List without for loop

names=["Hexin", "Zhangliang", ["Caijie", "LiSi"], "Liyun", "Tianjun", ' Guyun ', "Liyun"]print (Names[0:-1:2]) # The value of the index in the printed list is 0 to-1, with a step of 2print (Names[::1]) #打印列表中所有值

Results:

[' Hexin ', [' Caijie ', ' LiSi '], ' Tianjun '] [' Hexin ', ' Zhangliang ', [' Caijie ', ' LiSi '], ' Liyun ', ' Tianjun ', ' Guyun ', ' Liyun ']

Note: List printing belongs to "Gu Tou regardless of tail", such as print (Names[0:2]), and results can only output the first two values of the list.

Use the list to write the shopping cart program:

(1) After starting the program, let the user enter the salary, and then print the product list;

(2) The user enters the corresponding product number to purchase the product

(3) After the user enters the product number, the system detects whether the balance is sufficient, enough direct debit, not enough to prompt

(4) You can exit the shopping at any time and print the purchased goods and balances

shopping_list=[]product_list=[[' iphone ', 5800], [' Mac Pro ', 9800], [' Bike ', [+], [' Watch ', 10600], [' Coffee ', 31]]salary=input (' Input your Salary: ') if Salary.isdigit (): Salary=int (Salary) while True:for index, item in Enumerate (product_list): #enumerate: The index #print of the Read list (Product_list.index (item), item) is equivalent to the previous sentence print (index , item) user_choice=input (' Choose what to buy? ' If User_choice.isdigit (): #如果输入的是数字 user_choice=int (user_choice) #将字符窜转换为整型 if User_choice & Lt;len (product_list) and user_choice>=0: #如果用户输入的数字在user_choice列表的长度范围之内 p_item=product_list[user_choice                   ] #product_list列表中商品价格赋值给p_item if p_item[1] <= salary:shopping_list.append (P_item) SALARY-=P_ITEM[1] Print (' Added%s to shopping cart,your current banlance is \033[31;1m %s\033[0m '% (p_item,salary)) else:print (' \033[41;1m your balance is left only [%s] \033[0m '% salary) else:print (' product code[%s] is not exist '% user_choice) elif user_choice== ' Q ':  Print (' .... Shopping list ... ') for P in Shopping_list:print (p) print (' Your Current balance: ', salary) exit () else:print (' Invalid option ')

Two, the meta-group

Tuples once created cannot be modified, so they are also called read-only lists.

Tuples have only two methods: Count and Index

Tuple definition: names= (' Jim ', ' Lucy ')

Third, the dictionary

A dictionary is a Key-value data type and is unordered.

1. Dictionary-related operations

#字典定义: info={' stu001 ': ' Lily ',      ' stu002 ': ' Jack ',      ' stu003 ': ' John ',}print (info) print (info[' stu002 ']) # Print output stu002 value info["stu002"]= "Zhang San" #修改值info ["stu004"]= "Heqian" #新增 #del info #删除字典infodel info["stu001"]  # Delete the specified value print ("Post-operation dictionary >>>", info) b={    ' stu001 ': "Yanlin",    1:3,    2:5}info.update (b) #更新字典print (" Updated dictionary >>>, info) c=info.fromkeys ([6,7,8], "test") #初始化新字典 and assigns each key a value testprint ("Initialized dictionary >>>", c) Print (Info.items ()) #字典转成列表c =dict.fromkeys ([6,7,8],[1,{"name": "Micle"},234]) #初始化新字典, three keys will share a value print (c) c[7][1][ ' Name ']= "Cherry" #修改字典值print (c) Print ("--------dictionary loop------") for I in info:    print (I,info[i]) #推介使用此方法循环print ("---- -----") for K,v in Info.items ():    print (K,V)

Results:

{' stu003 ': ' John ', ' stu002 ': ' Jack ', ' stu001 ': ' Lily '} Jack's Dictionary after operation >>> {' stu003 ': ' John ', ' stu002 ': ' Zhang San ', ' stu004 ': ' Heqian '} updated dictionary >>> {1:3, ' stu002 ': ' Zhang San ', ' s tu001 ': ' Yanlin ', ' stu004 ': ' Heqian ', ' stu003 ': ' John ', 2:5} initialized dictionary >>> {8: ' Test ', 6: ' Test ', 7: ' Test '}dict_ite MS ([(1, 3), (' stu002 ', ' Zhang San '), (' stu001 ', ' Yanlin '), (' stu004 ', ' Heqian '), (' stu003 ', ' John '), (2, 5)]) {8: [1, {' name ': ' Mi Cle '}, 234], 6: [1, {' name ': ' Micle '}, 234], 7: [1, {' name ': ' Micle '}, 234]}{8: [1, {' name ': ' Cherry '}, 234], 6: [1, {' Nam  E ': ' Cherry '}, 234], 7: [1, {' name ': ' Cherry '}, 234]}--------Dictionary loop------1 3stu002 Zhang San stu001 yanlinstu004 HeQianstu003 John2 5---------1 3stu002 Zhang San stu001 yanlinstu004 HeQianstu003 John2 5

2. Dictionary Nesting

Av_catalog = {"    Europe and America": {"        www.youporn.com": ["a lot of free, the world's largest", "General quality"],        "www.pornhub.com": ["a lot of free, also very big", " Quality than Yourporn High "],        " letmedothistoyou.com ": [" mostly selfie, high-quality pictures a lot of "," resource is not much, update slow "],        " x-art.com ": [" The quality is very tall, really high "," all charges, Dick than please bypass "]    },    " Japan and South Korea ": {"        tokyo-hot ": [" The quality is not clear, the individual has not liked the Japanese and Korean fan "," Heard is charged "]    },    " mainland ": {        " 1024 ": [" All free, really good, good Life Peace "," server in foreign countries, slow "]    }}av_catalog[" mainland "[" 1024 "][1] + =", you can crawl down with crawlers "#修改内容print (av_catalog[" mainland "] [1024] ) #打印输出被修改的内容av_catalog. SetDefault ("Taiwan", {"www.baidu.com": [Up]}) #新增字典元素print (Av_catalog) av_ Catalog.setdefault ("Continent", {"www.baidu.com": [Up]}) print (Av_catalog)

Results:

[' All free, really good, good person life is safe ', ' server is abroad, slow, can crawl down with crawlers '] {' Japan and South Korea ': {' tokyo-hot ': [' The quality is not clear, the individual has not liked the Japanese and Korean fan ', ' heard is the charge ']}, ' mainland ': {' 1024 ': [' All free, really good, good Life peace ', ' server in foreign, slow, can crawl down with crawlers ']} Taiwan ': {' www.baidu.com ': [1, 2]}, ' Europe and America ': {' www.youporn.com ': [' a lot of free, the world's largest ', ' quality General '], ' letmedothistoyou.com ': [' Many are selfies, A lot of high-quality pictures ', ' Resources not much, update slow '], ' x-art.com ': [' high quality, really high ', ' all charges, dick than please bypass '], ' www.pornhub.com ': [' Many free, also very big ', ' quality is higher than Yourporn ']}}{ ' Japan and South Korea ': {' tokyo-hot ': [' The quality is not clear, the individual has not liked the Japanese and Korean fan ', ' heard is the charge ']}, ' mainland ': {' 1024 ': [' All free, really good, good people life safe ', ' server in foreign, slow, can crawl down with crawlers ']} Taiwan ': {' www.baidu.com ': [1, 2]}, ' Europe and America ': {' www.youporn.com ': [' a lot of free, the world's largest ', ' quality General '], ' letmedothistoyou.com ': [' Many are selfies, A lot of high-quality pictures ', ' Resources not much, update slow '], ' x-art.com ': [' high quality, really high ', ' all charges, dick than please bypass '], ' www.pornhub.com ': [' lots of free, also very big ', ' quality than yourporn highs ']}}

3, Level three menu implementation

data = {"Beijing": {"Chaoyang": {"Yi": [' Fried chicken ', ' Hamburg ', ' the ' "]," er ": [' Cola ', ' Sprite ']}," Changping ": { "San": [' 06 ', ' Yida ', ' 023 '], "si": [' rice ', ' Corn ']},}, "Sichuan": {"Chengdu": {"Shuangliu": [' fat Sausage powder ', ' spicy soup '], "Xindu": [' BBQ ', ' chicken ']}, "Mianyang": {"WU": [' beer ', ' Champagne ', ' duck neck '], "Liu" : [' Lemon ', ' orange ']},}, "Anhui": {"Hefei": {"qi": [' 011 ', ' 042 ', ' 063 '], "ba": [' 104 ', ' 105 ']}, "Huangshan": {"JIU": [' 066 ', ' ' ', ' 033 '], "shi": [' 304 ', ' 025 ']}}}ch1= Falsewhile not ch1:for i in Data:print (i) choice1=input (' >>>: ') if Choice1 in Data:whi            Le not ch1:for i2 in Data[choice1]: print ("\ T", i2) Choice2 = input (' >>>: ')                         If Choice2 in Data[choice1]: And not ch1:for i3 in Data[choice1][choice2]:Print ("\t\t", i3) Choice3 = input (' >>>: ') if choice3 in Data[choice1][choice 2]: For I4 in Data[choice1][choice2][choice3]: print ("\t\t\t", I                                4) Choice4=input (' is already the last level, press B to return to the upper >>>: ') if choice4== "B":                    Pass Elif choice4== "q": Ch1=true                        if choice3 = = "B": break elif Choice3 = = "Q": CH1 = True if Choice2 = = "B": break elif Choice2 = = "Q": Ch1 = True

Iv. Collection

A collection is an unordered, non-repeating combination of data.

list1=[1,4,5,6,3,5,3,6] #定义一个列表list1 =set (list1) #变成集合, go to Heavy list2=set ([3,5,33,67,8,6]) List3=set ([3,5,6]) List4=set ([ 4,2]) print (List1,type (list1)) print (List1.intersection (list2)) #取两个集合的交集print (List1.union (List2)) #取并集print ( List1.difference (List2)) #取差集, that is, in List1, print (List1.issubset (list2)) #子集print not in List2 (List1.issuperset (LIST2) Print (List3.issubset (list1)) #list3是list1的子集print (List1.symmetric_difference (List2)) #对称差集, which takes a value that is not shared by both parties print ("--- -------") Print (List2.isdisjoint (LIST4)) #判断是否有交集print (List1 & List2) #交集print (List2 | list1) #并集print (list1-list2 ) #差集print (list1 ^ list2) #对称差集list4. Add #添加一个值list4. Update ([00,22]) #添加多个值list4. Remove (2) #删除print (LIST4) print ( List1.pop ()) #删除任意一个值, and returns the deleted value print (List2.discard (")") #删除指定值, if the value is not present, the system will not error, unlike the Remove

Operation Result:

{1, 3, 4, 5, 6} <class ' Set ' >{3, 5, 6}{1,, 3, 4, 5, 6,, 8}{1, 4}falsefalsetrue{33, 1,, 4, 8}----------true{ 3, 5, 6}{33, 1, 8}{1, 3, 5, 6, 4,, 4}{33, 1,, 4, 8}{0, 4, 22}1none

Python base list, tuple, dictionary, collection usage

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.