Python self-study day-Two day (2)-python-list-tuples-dictionary, python-

Source: Internet
Author: User

Python self-study day-Two day (2)-python-list-tuples-dictionary, python-

List
Format: name = []
Name = [name1, name2, name3, name4, name5]


# List operations

Name. index ("name1") # query the name of the specified value. count ("name1") # query the name of the total number of specified values. clear ("name") # clear the list name. reverse ("name") # reverse the List Value name. sort ("name") # sort, with special characters in priority-numbers-UPPERCASE letters-lowercase letters name. extend ("name1") # extension. Add the value of another list to the current list.

# Add

Name. append ("name5") # append name. insert (1, "name1.5") # insert a specified position

# Delete

Name. remove ("name1") # Delete del name [0] # Delete the value of del name in the list according to the subscript # delete the name of the list. pop (0) # Delete the specified value. The default value is the last one.

# Querying select

Print (name [0], name [2]) # Read print (name [0: 2]) = print (name [: 2]) according to the subscript # Slice (continuous segment: regardless of the end, both 0 and-1 can be omitted.) print (name [-1]) #-1 gets the value of print (name [-2:]) at the last position. # obtain the last two values. The last one is-1, followed by-3,-2, and-1.

# Change update

Name [1] = "name1.5" # change the value of a specified subject

# List copy is divided into deep copy and light copy


Deep copy Copies the sublist in the list.

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]name1 = copy.deepcopy(name)name[4][1] = "name7"name[1] = "name2.1"print(name)print(name1)

Result)

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]['name1', 'name2', 'name3', 'name4', ['name5', 'name6']]


Light copy only copies the first layer of the list. If the values in the new file subcolumn are changed, the values in the sublist of the old file are not changed.

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]name1 = name.copy() = copy.copy(name) = name[:] = list(name)name[4][1] = "name7"name[1] = "name2.1"print(name)print(name1)

Result)

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]['name1', 'name2', 'name3', 'name4', ['name5', 'name7']

Tuples (immutable List)
Format: tuple = ("tu1", "tu2 ")
Like the list, it cannot be added, deleted, or modified. Only query (slice)

tuple = ("tup1", "tup2")print(tuple.count("tup1"))print(tuple.index("tup2"))

 

Exercise questions:

Program: Shopping Cart program

Requirements:

# Shoplist = [1, "iphone", 6000], [2, "mac pro", 12000], [3, "ipad air", 8000], [4, "chicken", 30], [5, "eggs", 5], [6, "bike ", 500] mall = [] salary = int (input ("please input your salary:") while True: for I in range (0, len (shoplist )): print (shoplist [I]) goodid = int (input ("Please enter the number you want to buy goods :")) -1 if int (shoplist [goodid] [2])> salary: print ("Don't buy goods you w Ant ") else: mall. append (shoplist [goodid]) salary = salary-shoplist [goodid] [2] yesorno = input (" To continue shopping? Input Y or N ") if yesorno = 'N': print (" Do you have bought the goods: % s, remaining sum: % s "% (mall, salary )) print ("Thanks for coming. ") break

Optimize the revised version:

# Optimized splist = [("iphone", 6000), ("mac pro", 12000), ("ipad air", 8000), ("chicken", 30 ), ("eggs", 5), ("bike", 500)] shop_list = [] salary1 = input ("please input your salary:") if salary1.isdigit (): # determine whether it is a number salary1 = int (salary1) while True: for index, I in enumerate (splist): print (index + 1, I) number = input ("Enter the product number to be selected:") if number. isdigit (): if int (number) <= len (splist) and int (number)> = 0: I F splist [int (number)-1] [1] <salary1: shop_list.append (splist [int (number)-1]) salary1-= splist [int (number) -1] [1] print ("the purchased item is % s, and the balance is \ 033 [41; 1 m % s \ 033 [0 m" % (shop_list, salary1) else: print ("your balance is \ 033 [31; 1 m % s \ 033 [0 m, select the product price as % s, so the current balance is not enough to buy this product. Please check if you want to purchase other products ?! "% (Salary1, splist [int (number)-1] [1]) else: print (" This item is not available, please reselect it! ") Elif number = 'N': print (" Your purchased item is % s, and the balance is \ 033 [41; 1 m % s \ 033 [0 m "% (shop_list, salary1) print (" thank you for coming. Welcome to come back next time! ") Exit () else: print (" enter the correct product number! ") Else: print (" enter the correct salary! ")

 

Dictionary: (unordered, no subscript, search for the corresponding value based on the key)
Format:
Info = {"key": "value ",}

Dictionary = {"n1": "5000", "n2": "5200", "n3": "2300", "n4 ": "9000"} # query print (dictionary ["n2"]) # Query when you know what the key is. If the key does not exist, print (dictionary. get ("n5") # If the key does not exist, "none" is returned. If the key does not exist, "value" is returned. Print ("n2" in dictionary) # determine whether the key exists. true or false is returned. in py2.7, the format is dictionary. has_key ("n3") # Add dictionary ["n2"] = "5100" dictionary ["n6"] = "800" print (dictionary) # Delete dictionary. pop ("n7") del dictionary ["n3"] # Delete the value corresponding to a known key. If no value exists, print (dictionary) is returned) # modify dictionary ["n2"] = "5100" dictionary ["n6"] = "800" # others # valuesprint (dictionary. values () # query all values without outputting keys # keysprint (dictionary. keys () # Only output key # setdefadicdictionary. setdefault ("n5", "100") # print the value if the key exists, and assign the new value if it does not exist. # update (replace the value if the key has the same value as the two dictionaries, insert if none exist.) dictionary = {"n1": "5000", "n2": "5200", "n3": "2300", "n4 ": "9000"} dictionary1 = {"n1": "8", "n3": "10000", "n6": "100", "n7 ": "4000"} dictionary. update (dictionary1) print (dictionary) {'n2 ': '000000', 'n4': '000000', 'n3 ': '000000', 'n7 ': '000000', 'n1 ': '8', 'n6': '000000'} # convert the dictionary into a list print (dictionary. items () dict_items ([('n2 ', '000000'), ('n3', '000000'), ('n4 ', '000000 '), ('n1 ', '123')])


# Dictionary Loop
Method 1:

for i in dictionary:    print(i, dictionary[i])


Method 2: The dictionary is converted to a list.

for key, value in dictionary.items():    print(key, value)

 

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.