(iii) Python dictionary meta-ancestor list try to apply

Source: Internet
Author: User

1. Use the Join method to add an underscore to each element of the list by stitching it into a string, Li = [' Alex ', ' Eric ', ' Rain ']

Li =  [' Boom ', ' TNT ', ' zhadan ']daying = ' _ '. Join (LI) print (daying)

2. Find the elements in the list, remove the spaces for each element, and look for all elements that begin with a or a and end with C.

Li = ["Alec", "Aric", "Alex", "Tony", "Rain"]

Tu = ("Alec", "Aric", "Alex", "Tony", "Rain")

DiC = {' K1 ': ' Alex ', ' K2 ': ' Aric ', ' K3 ': ' Alex ', ' K4 ': ' Tony '}

Consolidating the three fields together and then making a decision saves the amount of code:

Txts=li+list (TU) +list (dic.values) for TXT in txts:    print (Txt.strip ()) for TXT in txts:    txt.lower ()    if Txt.startswith ("a") and Txt.endswith ("C"):        print (TU)

List: []

Li = [' Alex ', ' Eric ', ' Rain ']

A. Calculate the length of the list and output using the Len function

Long =len (LI)

B. Append the element "seven" to the list and output the added list using the Append function

Li.append ("seven")

C. Please insert the element "Tony" in the 1th position of the list, and output the added list using the Insert function

Li.insert (0, "Tony")

D. Please modify the element in the 2nd position of the list to "Kelly" and output the modified list using the slicer modification

Li[1]= "Kelly"

E. Remove the Element "Eric" from the list and output the modified list using remove to specifically find the delete

Li.remove ("Eric")

F. Delete the 2nd element in the list and output the value of the deleted element and delete the element after the list using the POP function

Daying=li.pop (1) print (Daying,li)

G. Please invert all the elements in the list and output the inverted list using reverse transpose

Li.reverse () print (LI)

H. Use the Enumrate output list element and ordinal (ordinal starting from 100) to export the sequence number using enumerate

I=enumerate (LI) print (i)

Tuple ()

The majority of the available functions and lists of tuples are nothing, the main difference being that the first element of the tuple is immutable, cannot be added, and cannot be deleted.

Dictionary {}

Most of the functions that can be used in a dictionary are the same, but unlike tuples and lists, the contents of a dictionary are unordered, and the other two are ordered.

DiC = {' K1 ': "v1", "K2": "V2", "K3": [11,22,33]}

Use keys (), values () items () to output the key, value, and entire element of the dictionary separately

Updates can be used to update the dictionary if none in the dictionary, then add in

Dic.update (k4= "v4") print (DIC)

SetDefault can also be added

Dic.setdefault ("K1", "hah") print (DIC)

Use list (), tuple (), Dict (), and can be converted to a table-tuple dictionary separately

Boolean values that are false are:

0 {} [] () None ""

3. Element classification

There is a value set [11,22,33,44,55,66,77,88,99,90] that holds all values greater than 66 to the first key in the dictionary, and a value less than 66 to the value of the second key.

This is to save the value in the same location

lis=[11,22,33,44,55,66,77,88,99,90]dic={' K1 ': 0, ' K2 ': 0} For Li in Lis:    if li >:        dic[' K1 ']+=li    if Li <=:        dic[' K2 ']+=liprint (Dic.items ())

This is to save all the fields in the same location

lis=[11,22,33,44,55,66,77,88,99,90]dic={' K1 ': "", ' K2 ': ""}for Li in Lis:    if li >: dic[        ' K1 ']+=str (LI) C11/>if li <=:        dic[' K2 ']+=str (LI) print (Dic.items ())

and using the sort () method can be more concise

Li = [one, one, one, one, one, one, one, one, one, 90]li.sort ()    #排序z = li.index () = Len (li) dic = {"K1": Li[z + 1:l], "K2": l I[0:z]}print (DIC)

4, the output commodity list, the user enters the serial number, displays the user selected commodity commodity li = ["Mobile phone ", "Computer ", ' Mouse pad ', ' yacht ']

A. Allow users to add products

B. User input serial number display content

Li = ["Phone", "PC", "mouse pad", ' yacht ']dic={}for i,v in Enumerate (li,1):    dic[i]=vwhile True:    print (DIC)    Xuanzeqi = InP UT ("Add Item please press +, accurate display product please press *, exit please press Q")    if Xuanzeqi = = "+":        shangping=input ("Please add product name")        i+=1        dic[i]= shangping    elif xuanzeqi== "*":        shangpinghaoma=int (Input ("Please enter the product number you want to display accurately")        print (Dic[shangpinghaoma ])    elif xuanzeqi== "q":        break

5. Shopping Cart
Functional Requirements:
Require users to enter total assets, for example: 2000
Display the list of items, let the user select the item according to the serial number, add the shopping cart
Purchase, if the total amount of goods is greater than the total assets, indicating that the account balance is insufficient, otherwise, the purchase succeeds.

Goods = [{"Name": "Computer", "Price": 1999},{"name": "Mouse", "Price": 10},{"name": "Yacht", "Price": 20},{"name": "Beauty", "Price": 998 },]zongjiager=2000while True:    print (goods)    Goumaizongjia = 0    shangping=input ("Please enter the name of the product you want to buy, enter Q to exit the shopping") For    good in goods:        if  good[' name '] = = shangping:            Pannduanzhi = zongjiager-good["Price"]            if Panndu Anzhi < 0:                print ("Your balance is insufficient, the purchase is unsuccessful, your remaining amount is" +str (Zongjiager))            else:                Goumaizongjia + = good["Price"]                Zongjiager-=goumaizongjia                Print ("Successful purchase, your remaining amount is" +str (Zongjiager))    if shangping = = "Q":        print ("Thank You") Break        

6.

Use the Python developer program to automatically calculate the scenario:
Rooster 5 Text Money One, hen 3 text Money A, Chick 3 only a penny, with 100 money to buy 100 chickens, which cocks, hens, chickens must have, ask the rooster, mother
Chicken, how many chickens to buy just to fill 100 cents

Gongji_jiage=5gongji_zuidashuliangs = Range (1,21) muji_jiage = 3muji_zuidashuliangs = Range (1,34) Xiaoji_jiage = 3xiaoji _zhuidashuliangs = Range (1,101) ls=[]for Gongji_shuliang in gongji_zuidashuliangs: for    Muji_shuliang in Muji_ Zuidashuliangs: For        Xiaoji_shuliang in xiaoji_zhuidashuliangs:            if Gongji_shuliang*gongji_jiage+muji_ shuliang*muji_jiage+xiaoji_shuliang/xiaoji_jiage==100 and gongji_shuliang+ Muji_shuliang+xiaoji_shuliang = = 100:                ls.append ("Rooster", Gongji_shuliang, "hen", Muji_shuliang, "Chick", Xiaoji_shuliang)) print (len (LS)) print (LS)

One big problem is that variable names can't be set too long, or it makes it inconvenient to read code or write code.

7, user interactive display level three list production

A. Allowing users to add content

B. Allow users to choose to view a level of content

DIC = {

"Plants":

{"Herb":

["Morning Glory", "Melon leaf chrysanthemum", "gourd", "aster", "Winter Wheat", "beet"],

"Woody Plants":

["Arbor", "shrub", "half shrub", "pine", "fir", "camphor"),

"Aquatic Plants":

["Lotus", "thousand inflectional Vegetables", "calamus", "Yellow Calamus", "Calamus", "re-Force Flower", "Barracuda Grass"]},

"Animals":

{"Amphibians":

["Mountain Turtle", "turtle", "Stone Frog", "Baby Fish", "toad", "turtle", "Crocodile", "lizard", "snake"],

"Poultry":

["Pheasant", "Original Chicken", "ringing Chicken", "Chang Guo Ji", "Rooster", "Long Tail chicken", "black Bone Chicken"],

"Mammal Species":

["Tiger", "Wolf", "rat", "deer", "marten", "monkey", "tapir", "Sloth", "zebra", "Dog"]}

Kongzhiqi = truewhile Kongzhiqi = = True:print (Dic.keys ()) #一级菜单栏 panduan=input ("Please enter what you want to do, \n1: To see exactly what the list is, enter c,\n 2: Add list content Please enter B,\N3: Launch module Please enter Q ") #二级菜单栏 if Panduan = =" C ": Lb1=input (" Enter the list name you want to view ") while Kongzhiqi = = True : Print (Dic[lb1].keys ()) Panduan1 = input ("Please enter what you want to do, \n1: To see the contents of the list, enter c,\n2: Add list content Please enter B,\N3: Launch module Please enter q\ N4: Enter H to return to parent menu ") #三级菜单 if panduan1 = =" C ": lb2 = Input (" Enter the name of the list you want to view ") WHI Le Kongzhiqi = = True:print (dic[lb1][lb2]) panduan2=input ("Please enter what you want to do, \n1: Add List contents please lose  Into b,\n3: Launch module Please enter Q\N4: Enter H to return to the parent menu ") # Add content if panduan2 = =" B ": txt = Input ("Please enter the name you want to add") dic[lb1][lb2].append (TXT) # Return to Superior list El                         if panduan2 = = "H": Break # Exit Module Elif panduan2 = = "Q": KoNgzhiqi = False Print ("Successful exit") # Error instruction Else:                Print ("Please enter the correct instruction") #添加内容 elif panduan1 = = "B": txt = input ("Please enter the name you want to add")            Dic[lb1].setdefault (TXT) #返回上级列表 elif panduan1 = = "H": Break #退出模块            elif Panduan1 = = "Q": Kongzhiqi = False Print ("Exit successfully") #错误指令 Else:print ("Please enter the correct instruction") #添加内容 elif Panduan = = "B": txt= input ("Please enter the name you want to add") dic.setdef Ault (TXT) #退出模块 elif Panduan = = "Q": Kongzhiqi = False Print ("Exit successfully") #输入错误 Else:print ("please Enter the correct instruction ")

The above-mentioned three-level list of editing knowledge is purely using the IF statement and the while loop, but the number of code is very large basically in the list of each achievement to establish the corresponding function judgment, so that the usage of code is too low.

How to solve this problem, first of all, is to consider how to set the three-level list of functional options together, so that feature selection in depth to all levels of the list can be used.

Here is the following method, because the list of queries is a dictionary, when editing the query using the key property, then the key into a list, and stored in a new field, and continue to overlay, the code is as follows:

kongzhiqi = Truekey_case =[]while Kongzhiqi: #解决三层控制器想要在同一段代码中实现而不冲突, the most important thing is    The superposition of Key in the text dictionary during the continuous loop selection process.  Diejia = dic for key in Key_case:diejia = Diejia[key] Print ("All Current child nodes:", List (Diejia.keys ()), "\ n") Choice = Input ("Please enter the action you want to do, \n1: To see the contents of the list, enter c,\n2: Add the contents of the list, enter the B,\N3: Enter the module please input Q,\N4: Return to the upper level Please enter D") if choice.lower () = = "C": Chazh AO = input ("Please enter the name of the list to view") if Chazhao in Diejia:key_case.append (Chazhao) Else:print ("            The list name does not exist ") elif choice.lower () = =" B ": Tianjia = input (" Please enter what you want to add to this list ") if Tianjia in Diejia:            Print ("The list name already exists") Else:diejia[tianjia] = {} elif choice.lower () = = "D": if Key_case:        Key_case.pop () Else:print ("Already the most advanced") elif choice.lower () = = "Q": Kongzhiqi = False Print ("Exit successfully") Else:print ("Please enter the correct instruction") 

After so many of the topics of the attempt, the length of the Python editor is getting longer, the most profound experience in the editing process is Python a code indentation problem, Python is the indentation to determine the level of code, and so on, at first not familiar with the indentation of this problem took a lot of time,

There is the code comment problem, be sure to add comments, easy to check the code and identify the code, as well as the name of the variable problem, not too long, so that the view of the variable is unfavorable.

(iii) Python dictionary meta-ancestor list try to apply

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.