1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly learning python 2nd edition dec 2003 ISBN 0596002815

33 86 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 33
Dung lượng 538,73 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

But if you need to step through the items in adictionary it's easy: calling the dictionary keys method returns a list of all stored keys you can iterate through with a for.. 6.4.5 Dictio

Trang 1

>>> d2 # Order is scrambled.{'eggs': 3, 'ham': 1, 'spam': 2}

Trang 2

>>> 'ham' in d3 # Key membership test alternative1

>>> d2.keys( ) # Create a new list of my keys.['eggs', 'ham', 'spam']

in Chapter 14 and Chapter 21

In Chapter 10, you'll see that the last entry in Table 6-2 is

Trang 4

concatenation for dictionaries; it merges the keys and values ofone dictionary into another, blindly overwiting values of the

Trang 5

on for loops

Because dictionaries aren't sequences, you can't iterate overthem directly with a for statement, in the way you can withstrings and lists But if you need to step through the items in adictionary it's easy: calling the dictionary keys method returns

a list of all stored keys you can iterate through with a for Ifneeded, you can index from key to value inside the for loop asdone in this code

Python also lets us step through a dictionary's keys list withoutactually calling the keys method in most for loops For anydictionary D, saying for key in D: works the same as sayingthe complete for key in D.keys( ): This is really just anotherinstance of the iterators mentioned earlier, which allow the in

Trang 6

6.4.5 Dictionary Usage Notes

Here are a few additional details you should be aware of whenusing dictionaries:

Sequence operations don't work Dictionaries are

mappings, not sequences; because there's no notion of

ordering among their items, things like concatenation (anordered joining) and slicing (extracting contiguous section)simply don't apply In fact, Python raises an error when

your code runs, if you try to do such things

Assigning to new indexes adds entries Keys can be

created either when you write a dictionary literal (in whichcase they are embedded in the literal itself), or when youassign values to new keys of an existing dictionary object.The end result is the same

Keys need not always be strings Our examples used

strings as keys, but any other immutable objects (not lists)

work just as well In fact, you could use integers as keys,which makes a dictionary look much like a list (when

indexing, at least) Tuples are sometimes used as dictionarykeys too, allowing for compound key values And class

instance objects (discussed in Part VI) can be used as keystoo, as long as they have the proper protocol methods;

roughly, they need to tell Python that their values won'tchange, or else they would be useless as fixed keys

6.4.5.1 Using dictionaries to simulate flexible lists

Trang 7

When you use lists, it is illegal to assign to an offset that is offthe end of the list:

Trang 8

print 0

0

Trang 10

'web': 'www.rmi.net/~lutz',

'home': {'state': 'CO', 'zip':80501}}

This example uses a dictionary to capture object propertiesagain, but has coded it all at once (rather than assigning toeach key separately), and has nested a list and a dictionary torepresent structure property values To fetch components ofnested objects, simply string together indexing operations:

dict(name='mel', age=41) and dict([('name,'bob'),

('age',30)]) also build two-key dictionaries See Chapter 10,

Chapter 13, and Chapter 27 for more details

Trang 11

Besides being a convenient way to store information by key in your programs, some Python extensions also present interfaces that look and work the same as dictionaries For instance, Python's interface to dbm access-by-key files looks much like a dictionary that must be opened; strings are stored and fetched using key indexes:

of persistent Python objects) For Internet work, Python's CGI script support also presents a dictionary-like interface; a call to cgi.FieldStorage yields a

Trang 12

Besides lists, dictionaries are perhaps the most flexible built-in

data type in Python If you think of lists as ordered collections

of objects, dictionaries are unordered collections; their chiefdistinction is that items are stored and fetched in dictionaries by

key, instead of positional offset.

Being a built-in type, dictionaries can replace many of the

searching algorithms and data structures you might have toimplement manually in lower-level languagesindexing a

dictionary is a very fast search operation Dictionaries also

sometimes do the work of records and symbol tables used inother languages, can represent sparse (mostly empty) data

structures, and much more In terms of their main properties,dictionaries are:

Accessed by key, not offset

Dictionaries are sometimes called associative arrays or

hashes They associate a set of values with keys, so thatyou can fetch an item out of a dictionary using the key thatstores it You use the same indexing operation to get

components in a dictionary, but the index takes the form of

a key, not a relative offset

Unordered collections of arbitrary objects

Unlike lists, items stored in a dictionary aren't kept in anyparticular order; in fact, Python randomizes their order inorder to provide quick lookup Keys provide the symbolic(not physical) location of items in a dictionary

Trang 13

Like lists, dictionaries can grow and shrink in place (withoutmaking a copy), they can contain objects of any type, andsupport nesting to any depth (they can contain lists, otherdictionaries, and so on)

Of the category mutable mapping

Dictionaries can be changed in place by assigning to

indexes, but don't support the sequence operations thatwork on strings and lists Because dictionaries are

unordered collections, operations that depend on a fixedorder (e.g., concatenation, slicing) don't make sense

Instead, dictionaries are the only built-in representative ofthe mapping type categoryobjects that map keys to values

Table 6-2 summarizes some of the most common dictionaryoperations (see the library manual for a complete list)

Dictionaries are written as a series of key:value pairs,

separated by commas, and enclosed in curly braces.[4] An

Trang 14

be nested by writing one as a value inside another dictionary, orwithin a list or tuple

[4] The same note about the relative rarity of literals applies here: dictionaries are often built up

by assigning to new keys at runtime, rather than writing literals But see the following section on changing dictionaries; lists and dictionaries are grown in different ways Assignment to new keys works for dictionaries, but fails for lists (lists are grown with append instead).

len(d1) Length (number stored entries)

D2[key] = 42del d2[key] Adding/changing, deleting

D4 = dict(zip(keyslist, valslist)) Construction ( Chapter 10 )

Trang 15

related topics: the lambda expression, functional programmingtools such as map and list comprehensions, generators, andmore Part of the art of using functions lies in the interfacesbetween them, so we will also explore some general functiondesign principles here Because this is the last chapter in Part

This chapter introduces a collection of more advanced function-IV, we'll close with the usual sets of gotchas and exercises tohelp you start coding the ideas you've read about

Trang 17

In this chapter, we meet Python's two main looping

constructsstatements that repeat an action over and over Thefirst of these, the while loop, provides a way to code generalloops; the second, the for statement, is designed for steppingthrough the items in a sequence object and running a block ofcode for each item

There are other kinds of looping operations in Python, but thetwo statements covered here are the primary syntax providedfor coding repeated actions We'll also study a few unusual

statements such as break and continue here, because they areused within loops

Trang 18

paradigm to apply, and can cut development time

substantially when used well

Trang 19

Chapter 12 looked at basic function definition and calls As

we've seen, the basic function model is simple to use in Python

This chapter presents the details behind Python's scopesthe places where variables are defined, as well as argument

passingthe way that objects are sent to functions as inputs.

Trang 20

At this point in the book, you have been exposed to a fairly

complete survey of the more formal aspects of the language(the syntax, the data types, etc.) In this chapter, we'll "stepout of the classroom" by looking at a set of basic computingtasks and examining how Python programmers typically solvethem, hopefully helping you ground the theoretical knowledgewith concrete results

Python programmers don't like to reinvent wheels when theyalready have access to nice, round wheels in their garage Thus,the most important content in this chapter is the description ofselected tools that make up the Python standard librarybuilt-infunctions, library modules, and their most useful functions andclasses While you most likely won't use all of these in any oneprogram, no useful program avoids all of these Just as Pythonprovides a list object type because sequence manipulations

occur in all programming contexts, the library provides a set ofmodules that will come in handy over and over again Beforedesigning and writing any piece of generally useful code, check

to see if a similar module already exists If it's part of the

standard Python library, you can be assured that it's been

heavily tested; even better, others are committed to fixing anyremaining bugsfor free

The goal of this chapter is to expose you to a lot of differenttools, so that you know that they exist, rather than to teach youeverything you need to know in order to use them There arevery good sources of complementary knowledge once you'vefinished this book If you want to explore more of the standardlibrary, the definitive reference is the Python Library Reference,currently over 600 pages long It is the ideal companion to thisbook; it provides the completeness we don't have the room for,and, being available online, is the most up-to-date description

Trang 21

Python in a Nutshell provides a thorough yeteminently readable

and concise description of the language and standard library Aswe'll see in Section 27.1, Python comes with tools that makeself-learning easy as well

Just as we can't cover every standard module, the set of taskscovered in this chapter is necessarily limited If you want more,

check out the Python Cookbook (O'Reilly), edited by David

Ascher and Alex Martelli This Cookbook covers many of thesame problem domains we touch on here but in much greaterdepth and with much more discussion That book, leveragingthe collective knowledge of the Python community, provides amuch broader and richer survey of Pythonic approaches to

common tasks

This chapter limits itself to tools available as part of standardPython distributions The next two chapters expand the scope

to third party modules and libraries, since many such modulescan be just as valuable to the Python programmer

This chapter starts by covering common tasks which apply tofundamental programming conceptstypes, data structures,

strings, moving on to conceptually higher-level topics like filesand directories, Internet-related operations and process

launching before finishing with some nonprogramming taskssuch as testing, debugging, and profiling

Trang 22

In Part IV, we study the Python functiona package of codethat can be called repeatedly, with different inputs andoutputs each time We've already been calling functionsearlier in the book: open, to make a file object, for

instance Here, the emphasis will be on coding user-defined functions, which compute values, perform part of

a program's overall logic, or otherwise wrap code for easyreuse

Trang 23

expand on the details introduced here in later chapters of thispart of the book; but in their basic form, Python classes areeasy to understand.

Trang 24

In Part III, we looked at basic procedural statements in Python.Here, we'll move on to explore a set of additional statementsthat create functions of our own In simple terms, a function is

a device that groups a set of statements, so they can be runmore than once in a program Functions also let us specify

parameters that serve as function inputs, and may differ eachtime a function's code is run Table 12-1 summarizes the

primary function-related tools we'll study in this part of thebook

Trang 25

' repr ', ' rmul ', ' setattr ', ' setitem ', ' setslice ', ' str ', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Trang 26

>>> mydir([ ]) # What are the attributes of lists?

['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']You can then explore any Python object:

>>> mydir(( )) # What are the attributes of tuples?[ ] # Note: no "normal" attributes

>>> import sys # What are the attributes of files?

>>> mydir(sys.stdin) # What are the attributes of files?

['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write',

Trang 27

This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the

interpreter

Dynamic objects:

argv command line arguments; argv[0] is the script pathname if known path module search path; path[0] is the script directory, else '' modules dictionary of loaded modules

Trang 28

gethostbyaddr( ) map an IP number or hostname to DNS info

getservbyname( ) map a service name and a protocol name to a port

ATTRIBUTES DICTIONARYLITERALS MAPPINGS SHIFTING

AUGMENTEDASSIGNMENT ELLIPSIS METHODS SLICINGS

BACKQUOTES EXCEPTIONS MODULES SPECIALATTRIBUTESBASICMETHODS EXECUTION NAMESPACES SPECIALIDENTIFIERS

Trang 29

CALLABLEMETHODS FORMATTING OBJECTS SUBSCRIPTS

CALLS FRAMEOBJECTS OPERATORS TRACEBACKS

CLASSES FRAMES PACKAGES TRUTHVALUE

CODEOBJECTS FUNCTIONS POWER TUPLELITERALSCOERCIONS IDENTIFIERS PRECEDENCE TUPLES

COMPARISON IMPORTING PRINTING TYPEOBJECTSCOMPLEX INTEGER PRIVATENAMES TYPES

help> quit

>>>

Trang 30

Part V explores Python modules Modules are packages ofnames that usually correspond to source files and serve aslibraries of tools for use in other files and programs Weintroduced modules very early (in Part I) as a way to

retain and run code Here, we fill in the remaining details

on this subject, and study some advanced module-relatedtopics, such as package (directory) imports

Trang 31

In Part III, we study Python's procedural statement set:statements that select from alternative actions, repeatoperations, print objects, and so on Since this is our firstformal look at statements, we will also explore Python'sgeneral syntax model As we'll see, Python has a familiarand simple syntax model, though we often type much less

in Python statements than in some other languages

We'll also meet the boolean expressions in conjunctionwith conditional statements and loops, and learn aboutPython documentation schemes while studying the syntax

of documentation strings and comments At an abstractlevel, the statements we'll meet here are used to createand process the objects in Part II By the end of this part,you will be able to code and run substantial Python

program logic

Ngày đăng: 19/04/2019, 10:10

TỪ KHÓA LIÊN QUAN