#父与子的编程之旅 # 12th Chapter

Source: Internet
Author: User

The 12th chapter mainly introduces lists and dictionaries. The list is very well understood, and the same as the C language inside the array, the dictionary is the new knowledge in Python, focus on.

    • List
    1. What is a list? A list can be said to be a large collection surrounded by square brackets. Such as: Can be a collection of strings, family = [' Mom ', ' Dad ', ' Me '], can be a collection of numbers, luckynumbers = [1,2,3,4,5]; can be a mix of collections, including numbers, strings, objects and even other lists, my_list = [5, ' HELLO ', myteacher,7,another_list,[1,2,3]]
    2. How do I create a list? NewList = [], this is an empty list, or, NewList = [1,2,3,4], a list of the contents of a given list
    3. Add an element to a list?

Append () Adds an element to the end of the list. e.g. friends.append (' David ')

Extend () adds multiple elements to the end of the list. e.g. friends.extend ([' P ', ' Q ', ' R '])

Insert () Adds an element to a location in the list, not necessarily at the end. e.g. Friends.insert (2, ' Z ')

Append () and extend () are different when adding elements, extend () is adding multiple elements directly to the end, and append () adds multiple elements to the end as a list. Anyway append () can only add one element at the end, if I want to force the addition of more than one element, then it will be more than one element as a list to add, imagine the list can also be a list of elements ah.

4. How do I delete an element from a list? Suppose letters = [' A ', ' B ', ' C ']

Remove () Removes the element based on the value of the element.  e.g. Letters.remove (' C ')

Del allows you to remove an element from the list using an index. E.g del Letters[2]

Pop () There is nothing in the parentheses when you take the last element of the list to you, of course, the index in parentheses is deleted according to the index. e.g. Lastletter = Letters.pop () e.g. second = Letters.pop (1)

5. How do I determine if a list contains a value? Use the IN keyword. PS: This in keyword also applies in dictionaries.

6. How do I sort the list? Order sorted with sort (), reverse order with reverse () or with sort (reverse = True) e.g. Letters.sort () e.g. letters.reverse (e.g) Letters.sort rever SE = True) These are the sort methods that change the original list, and the other Sort method sorted () Sorts the list copy on the basis of the original list without changing it, e.g. new = sorted (original), Here the original list original and the sorted list new are present.

7. How do I create a copy of a list? New = original[:]

8. What is a tuple? Tuples are immutable lists, which cannot be added to remove elements more than to be sorted, using parentheses to define them. e.g. My_tuple = ("Red", "Blue", "green")

9. What is a double list? Similar to the two-tuple array, the main note is that the indexes are all starting from 0. e.g. classmarks[0][2] represents an element in the third column of the first row.

    • Dictionary

1. What is a dictionary? Like a phone book, a person's name and name correspond to the same number, the dictionary has a key and a key corresponding to the value, called the key-value pair. A dictionary is a collection of key-value pairs. Create an empty Dictionary Phonenum = {}

2. How do I add an item to the dictionary? One is Phonenum = {"John": "12345"}, the other is phonenum["Jhon"] = "12345", the two effects are the same, but in the dictionary add the key value pair is not a fixed order, the first added key value pair printed out may be in the back.

3. How do I use the key to find an entry? The keys () method lists all the keys in the dictionary, and the values () method lists all of the value in the dictionary, and Phonenum[key] can list the values in the dictionary according to the index, and key represents the index

4. How do I delete an entry in a dictionary?

Del deletes entries based on keywords. E.g del phonenum["Jhon"]

Clear () clears the dictionary. e.g. Phonenum.clear ()

    • The similarities and differences between lists and dictionaries

Same point:

Lists and dictionaries are a collection that can contain numbers, strings, objects, and even collections of other collections.

Provides a way to find entries.

Dissimilar points:

The list is ordered and the dictionary is unordered. (dictionaries can be sorted according to their values or alphabetically by key, but the whole dictionary cannot be sorted)

The elements in the list use index access and the elements in the dictionary use keys to access

#动手试一试T1. Write a program that gives the user 5 names. The program will save these 5 names in a list, #最后打印出来. Like this: ' Enter 5 names:tony Paul Nick Michel Kevin the names is Tony Paul Nick Michel kevin ' names = []PR int ' Enter 5 names: ' For I in Range (5): Names.append (Raw_input ()) print ' The names is ', for j in Range (5): Print name S[J], #动手试一试T2. Modify the first question of the program, requires not only to display the original name list, but also to display the sorted list names = []print ' Enter 5 names: ' For I in Range (5): Names.append (Raw_input ()) print ' T He names is ', for j in Range (5): Print Names[j],printsortednames = Names[:]sortednames.sort () print ' The sorted names AR E ', for K in range (5): Print Sortednames[k], #动手试一试T3. Modify the first program to show only the 3rd name that the user typed, like this: #The third name you entered is:nicknames = []print ' Enter 5 names: ' For I in Range (5): NA Mes.append (Raw_input ()) print ' The third name you entered is: ', names[2] #动手试一试T4. Modify the program for question 1th so that the user replaces one of the names. The user should be able to choose which name to replace and then type a new name. #最后显示这个新的列表: "Enter 5 names:tonypaulnickmichelkevinthe names is Tony Paul Nick Michel kevinreplace one name. Which one? (1-5): 4New name:peterthe Names is Tony Paul Nick Peter Kevin ' names = []print ' Enter 5 names: ' For I in Range (5): Names.append (Raw_input ()) PR int ' The names is ', for j in Range (5): Print names[j],printn = Int (raw_input (' Replace one name '). Which one? (1-5): ') names[n-1] = raw_input (' New name: ') print ' The names is ', for K in range (5): Print Names[k], #动手试一试T5. Write a dictionary program that allows users to add words and definitions, and then find these words. Make sure that the user is aware when the word # is not found. When running, it should be like this: "' Add or look up a word (a/l)?" Atype the Word:computertype the defiition:a machine that does very fast Mathword added! Add or look up a word (a/l)? 1Type the Word:computera machine, does very fast mathadd or look up a word (a/l)? 1Type the word:qwertythat word isn ' T in the dictionary yet. " Dictionary = {}move = raw_input (' Add or look up a word (a/l)? ')    if move = = ' a ': InputName = raw_input (' Type the word: ') dictionary[inputname] = raw_input (' Type the definition: ')    print ' Word added! ' move = Raw_input (' Add or look up a word (a/l)? ') if move = = ' L ': thenname = raw_input (' Type the word: ') if thenname in Dictionary:print dictionary[thenname] move = raw_input (' Add or look    Up a word (a/l)? ') Thenname = Raw_input (' Type the word: ') if thenname not in dictionary:print "so word isn ' t in the dictionary y ET. "

  

#父与子的编程之旅 # 12th Chapter

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.