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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值