`
sillycat
  • 浏览: 2555825 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

DiveIntoPython(二)tuples

阅读更多
DiveIntoPython(二)tuples

英文书地址:
http://diveintopython.org/toc/index.html

3.3 Introducing Tuples     tuple ['tʌpl] n. 元组,重数
A tuple is an immutable list. A tuple can not be changed in any way once it is created.
examples:
>>> t = ("a","b","mpi","z","example")
>>> t
('a', 'b', 'mpi', 'z', 'example')
>>> t[0]
'a'
>>> t[-1]
'example'
>>> t[1:3]
('b', 'mpi')

A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

Negative indices count from the end of the tuple, just as with a list.    indice  n. 指数;标记体

Slicing works too, just like a list. Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.

Tuples Have No Methods
examples:
>>> t
('a', 'b', 'mpi', 'z', 'example')
>>> t.append("new")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove("a")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.index("mpi")
2
>>> "mpi" in t
True

The book says that You can't find elements in a tuple. Tuples have no index method.
This is not suit for the version 2.6, because we get index number 2 in the example

You can, however, use in to see if an element exists in the tuple.

So what are tuples good for?
Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

It makes your code safer if you “write-protect” data that does not need to be changed.

Remember that I said that dictionary keys can be integers, strings, and “a few other types”? Tuples are one of those types. Tuples can be used as keys in a dictionary, but lists can't be used this way.Actually, it's more complicated than that. Dictionary keys must be immutable. Tuples themselves are immutable, but if you have a tuple of lists, that counts as mutable and isn't safe to use as a dictionary key. Only tuples of strings, numbers, or other dictionary-safe tuples can be used as dictionary keys.

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.

3.4 Declaring variables
Python has local and global variables like most other languages, but it has no explicit variable declarations. Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.

examples:
if __name__ == "__main__":
    myParams = {"server":"mpilgrim", \
                       "database":"masteer", \
                       "uid" : "sa" \
                      }
Notice the indentation. An if statement is a code block and needs to be indented just like a function.

Also notice that the variable assignment is one command split over several lines, with a backslash (“\”) serving as a line-continuation marker.

When a command is split among several lines with the line-continuation marker (“\”), the continued lines can be indented in any manner; Python's normally stringent indentation rules do not apply. If your Python IDE auto-indents the continued line, you should probably accept its default unless you have a burning reason not to.

3.4.1 Referencing Variables
examples:
>>> x
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 1
>>> x
1

3.4.2 Assigning Multiple Values at Once     assign [ə'sain]  vt. 分配;指派;赋值
examples:
>>> v = ('a','b','e')
>>> (x,y,z) = v
>>> x
'a'
>>> y
'b'
>>> z
'e'

Assigning Consecutive Values
examples:
>>> range(7)
[0, 1, 2, 3, 4, 5, 6]
>>> (MONDAY,TUESDAY,WEDNESDAY,TRURSDAY,FRIDAY,SATURDAY,SUNDAY) = range(7)
>>> MONDAY
0
>>> SUNDAY
6

The built-in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a zero-based list counting up to but not including the upper limit. (If you like, you can pass other parameters to specify a base other than 0 and a step other than 1. You can print range.__doc__ for details.)

You can also use multi-variable assignment to build functions that return multiple values, simply by returning a tuple of all the values. The caller can treat it as a tuple, or assign the values to individual variables.

3.5. Formatting Strings
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.
String formatting in Python uses the same syntax as the sprintf function in C.

examples:
>>> k = 'uid'
>>> v = 'sa'
>>> "%s=%s" % (k,v)
'uid=sa'

The whole expression evaluates to a string. The first %s is replaced by the value of k; the second %s is replaced by the value of v. All other characters in the string (in this case, the equal sign) stay as they are.

You might be thinking that this is a lot of work just to do simple string concatentation, and you would be right, except that string formatting isn't just concatenation. It's not even just formatting. It's also type coercion.

String Formatting vs. Concatenate
examples:
>>> uid = 'sa'
>>> pwd = 'secret'
>>> print pwd + ' is not a good password for ' + uid
secret is not a good password for sa
>>> print '%s is not a good password for %s ' % (pwd,uid)
secret is not a good password for sa
>>> userCount = 6
>>> print 'Users connected: %d' % (userCount,)
Users connected: 6
>>> print 'Users connected: ' + userCount
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

+ is the string concatenation operator.
In this trivial case, string formatting accomplishes the same result as concatentation.

In fact, you can always include a comma after the last element when defining a list, tuple, or dictionary, but the comma is required when defining a tuple with one element. If the comma weren't required, Python wouldn't know whether (userCount) was a tuple with one element or just the value of userCount.

String formatting works with integers by specifying %d instead of %s.

Trying to concatenate a string with a non-string raises an exception. Unlike string formatting, string concatenation works only when everything is already a string.

Formatting Numbers
examples:
>>> print "Today's stock price: %f" % 50.4625
Today's stock price: 50.462500
>>> print "Today's stock price: %.2f" % 50.5625
Today's stock price: 50.56
>>> print "Change since yesterday: %+.2f" % 1.5
Change since yesterday: +1.50

The %f string formatting option treats the value as a decimal, and prints it to six decimal places.

The ".2" modifier of the %f option truncates the value to two decimal places.

You can even combine modifiers. Adding the + modifier displays a plus or minus sign before the value. Note that the ".2" modifier is still in place, and is padding the value to exactly two decimal places.

3.6 Mapping Lists
One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list.

Introducing List Comprehensions

examples:
>>> li = [1,9,8,4]
>>> [elem * 2 for elem in li]
[2, 18, 16, 8]
>>> li
[1, 9, 8, 4]
>>> li = [elem * 2 for elem in li]
>>> li
[2, 18, 16, 8]

Python loops through li one element at a time, temporarily assigning the value of each element to the variable elem. Python then applies the function elem*2 and appends that result to the returned list.

Note that list comprehensions do not change the original list.

in early examples:
["%s=%s" % (k, v) for k, v in params.items()]
First, notice that you're calling the items function of the params dictionary. This function returns a list of tuples of all the data in the dictionary.

The keys,values,and items Functions
examples:
>>> params = {'server':'mpilgrim','database':'master','uid':'sa','pwd':'secret'}
>>> params.keys()
['pwd', 'database', 'uid', 'server']
>>> params.values()
['secret', 'master', 'sa', 'mpilgrim']
>>> params.items()
[('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')]

The keys method of a dictionary returns a list of all the keys. The list is not in the order in which the dictionary was defined (remember that elements in a dictionary are unordered), but it is a list.

The values method returns a list of all the values. The list is in the same order as the list returned by keys, so params.values()[n] == params[params.keys()[n]] for all values of n.

the items method returns a list of tuples of the form (key, value). The list contains all the data in the dictionary.

List Comprehensions in buildConnectionString Step by Step

examples:
>>> params
{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}
>>> params.items()
[('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')]
>>> [k for k,v in params.items()]
['pwd', 'database', 'uid', 'server']
>>> [v for k,v in params.items()]
['secret', 'master', 'sa', 'mpilgrim']
>>> ['%s=%s' % (k,v) for k,v in params.items()]
['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim']

3.7 Joining Lists and Splitting Strings
3.7.1 Historical Note on String Methods

To join any list of strings into a single string, use the join method of a string object.

The join method joins the elements of the list into a single string, with each element separated by a semi-colon. The delimiter doesn't need to be a semi-colon; it doesn't even need to be a single character. It can be any string.

examples:
>>> params = {"server":"madsf","database":"master","uid":"sa"}
>>> ["%s = %s" % (k,v) for k,v in params.items()]
['database = master', 'uid = sa', 'server = madsf']
>>> ";".join(["%s = %s" % (k,v) for k,v in params.items()])
'database = master;uid = sa;server = madsf'

examples:
>>> li = ['server=seradsf','uid=sa','database=master','pwd=secret']
>>> s = ";".join(li)
>>> s
'server=seradsf;uid=sa;database=master;pwd=secret'
>>> s.split(";")
['server=seradsf', 'uid=sa', 'database=master', 'pwd=secret']
>>> s.split(";",1)
['server=seradsf', 'uid=sa;database=master;pwd=secret']

split reverses join by splitting a string into a multi-element list. Note that the delimiter (“;”) is stripped out completely; it does not appear in any of the elements of the returned list.

split takes an optional second argument, which is the number of times to split.

When I first learned Python, I expected join to be a method of a list, which would take the delimiter as an argument. Many people feel the same way, and there's a story behind the join method. Prior to Python 1.6, strings didn't have all these useful methods. There was a separate string module that contained all the string functions; each function took a string as its first argument. The functions were deemed important enough to put onto the strings themselves, which made sense for functions like lower, upper, and split. But many hard-core Python programmers objected to the new join method, arguing that it should be a method of the list instead, or that it shouldn't move at all but simply stay a part of the old string module (which still has a lot of useful stuff in it). I use the new join method exclusively, but you will see code written either way, and if it really bothers you, you can use the old string.join function instead.
分享到:
评论

相关推荐

    深入Python-从新手到专业人士的PythonDive Into Python - Python from novice to pro

    ### 深入Python-从新手到专业人士的Python Dive Into Python - Python从新手到专业 #### 背景介绍 《深入Python》是一本面向具有一定编程基础的学习者撰写的教材,旨在帮助读者从一个初学者成长为能够熟练运用...

    Tuples in Python Programming Python 编程中的元组.doc

    ### Python编程中的元组 #### 引言 Python是一种广泛使用的高级编程语言,因其简洁、易读性而受到开发者的青睐。Python支持多种数据类型,包括列表(List)、元组(Tuple)、字典(Dictionary)等。其中,元组作为...

    python.rar

    这本书,"Dive Into Python"的中文版,由Mark Pilgrim撰写,是一本广泛认可的Python自学教材。它以清晰易懂的方式介绍了Python的核心概念,帮助读者快速上手并深入理解这门强大的语言。 首先,书中的"Chapter 1: ...

    Python for Bioinformatics 第二版,最新版

    5.6.2 Consolidate Multiple DNA Sequences into One FASTA File 102 5.7 ADDITIONAL RESOURCES 102 5.8 SELF-EVALUATION 103 Chapter 6 Code Modularizing 105 6.1 INTRODUCTION TO CODE MODULARIZING 105 6.2 ...

    11_delete_tuples.py

    11_delete_tuples

    10_update_tuples.py

    10_update_tuples

    09_access_tuples.py

    09_access_tuples

    quick python book 第三版

    The Quick Python Book, Third Edition is a comprehensive guide to the Python language by a Python authority, Naomi Ceder. With the personal touch of a skilled teacher, she beautifully balances details ...

    Learning Python

    Dictionaries, lists, tuples, and other data structures specific to Python receive plenty of attention including complete examples., Authors Mark Lutz and David Ascher build on that fundamental ...

    Coding Games in Python

    A visual step-by-step guide to writing code in Python. Beginners and experienced ...With coding theory interwoven into the instructions for building each game, learning coding is made effortless and fun.

    The Quick Python Book 3rd

    Initially Guido van Rossum's 1989 holiday project, Python has grown into an amazing computer language. It's a joy to learn and read, and powerful enough to handle everything from low-level system ...

    python教程中英文对照

    2. **高效的数据结构**:Python内建了多种高效的数据结构,如列表(lists)、元组(tuples)、字典(dictionaries)等,这些结构能够极大地提高数据处理的效率。 3. **面向对象编程**:Python支持面向对象的编程方式,用户...

    Functional Python Programming(PACKT,2015)

    Python’s easy-to-learn and extensible abilities offer a number of functional programming features for you to bring into your workflow, especially in the realm of data science. If you’re a Python ...

    Modern.Python.Cookbook.epub

    By exposing Python as a series of simple recipes, you can gain insight into specific language features in a particular context. Having a tangible context helps make the language or standard library ...

    Python课程资料.rar

    Python课程资料,可使用Jupyter Notebook打开: 1. Python basic ...4.Lists, Tuples, Sets & Dictionaries 5. Functions 6. Strings & Regular expressions …… 浙江理工大学Python课程所使用资料

    tuples:JavaScript中类似元组的微小实现

    元组 JavaScript中一个类似于元组的小实现。 安装 npm install tuples 用法 const { tuple , fst , snd , swap } = require ( 'tuples' ) ... 提取一对的第二个成分。 掉期(t) 交换一对的组件。 执照

    python官方教程

    列表(List)、元组(Tuples)、集合(Sets)和字典(Dictionaries)是Python中的核心数据结构,教程通过介绍它们的使用方法和特点,帮助学习者理解如何在程序中存储和管理数据。此外,还涉及到range()函数的使用、...

    python cookbook 英文

    ### Python Cookbook 英文版知识点概述 #### 一、Python快捷操作 本章节主要介绍了Python中的一些基础且实用的操作技巧。 ##### 1.1 无需使用临时变量交换值 在Python中,可以轻松地在不使用任何临时变量的情况...

    python基础语法合集68页.pdf

    在Python中,变量的创建需要赋值,变量类型包括Numbers(数字)、Strings(字符串)、Lists(列表)、Tuples(元组)和Dictionaries(字典)等。数字类型有int、float、long和complex,其中,Python 3.x中long类型与...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...

Global site tag (gtag.js) - Google Analytics