- 浏览: 2491091 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
DiveIntoPython(一)first program
英文书地址
http://diveintopython3.org/
下载得到PDF版本
http://diveintopython3.org/d/diveintopython3-pdf-r860-2010-01-13.zip
解开压缩得到文件diveintopython3-r860.pdf和很多example.
python本身的官方文档
http://docs.python.org/3.1/
以上是版本python3,后来再使用中发现google app engine和django都还没有支持到python3,所以我本机安装的python2.6.4,所以决定先从小版本看起。
英文书地址:
http://diveintopython.org/toc/index.html
chapter 1. Installing Python
1.1 介绍了两种方式下载python
1如果要最新版本,请下载官方版本,下载地址:http://www.python.org/
得到文件python-2.6.4.msi,双击安装
2比较实用,笔者推荐activePython,下载地址:http://www.activestate.com/activepython/downloads/
得到文件ActivePython-2.6.4.10-win32-x86.msi,双击安装
1.2 The Interactive Shell
An interactive shell can evaluate arbitrary statements and expressions.This is extremely useful for debugging,quick hacking and testing.
chapter 2.Your First Python Program
odbchelper.py in examples:
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
the output of odbchelper.py will look like this:
pwd=secret;database=master;uid=sa;server=mpilgrim
2.2 Declaring Function
def buildConnectionString(params):
python do not specify the type about return value and arguments.
2.2.2 How Python's Datatypes Compare to Other Programming Languages
statically typed language
A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language
A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language
A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language
A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.
2.3.Documenting Functions
def buildConnectString(params):
""" Build a connection string from a dictionary of parameters.
Return string """
Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.
2.4 Everything Is an Object
I type follow commands in my interactive shell:
>>> import odbchelper
>>> params = {"tt1":"tt1"}
>>> print odbchelper.buildConnectionString(params)
tt1=tt1
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary
Returns string.
2.4.1 The Import Search Path:
>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info', 'E:\\book\\opensource\\python\\diveintopython-5.4\\py']
You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.
2.4.2 What's an Object
All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.
everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
2.5 Indenting Code indent [in'dent, 'indent] n. 凹痕;订货单;契约;缩进 vt. 缩排
Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords.
bracket ['brækit] n. 支架;括号;墙上凸出的托架
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.
2.6 Testing Modules
Modules are objects, and all modules have a built-in attribute __name__ and __doc__.
Chapter 3 . Native Datatypes
3.1 Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
A dictionary in Python is like an instance of the Hashtable class in Java.
3.1.1. Defining Dictionaries
example:
>>> d = {"server":"mpilogrim","database":"master"}
>>> d
{'database': 'master', 'server': 'mpilogrim'}
>>> d["server"]
'mpilogrim'
>>> d["database"]
'master'
>>> d["ccc"]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'ccc'
the whole set of elements is enclosed in curly braces.And you can get values by key, but you can't get keys by value.
3.1.2 Modifying Dictionaries
>>> d["database"] = "pubs"
>>> d
{'database': 'pubs', 'server': 'mpilogrim'}
>>> d["uid"] = "sillycat"
>>> d
{'database': 'pubs', 'uid': 'sillycat', 'server': 'mpilogrim'}
You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.
examples:
>>> d["key"] = "other value"
>>> d
{'key': 'other value'}
>>> d["Key"] = "third value"
>>> d
{'Key': 'third value', 'key': 'other value'}
examples:
>>> d = {}
>>> d
{}
>>> d["retrycount"] = 3
>>> d
{'retrycount': 3}
>>> d[42] = "douglas"
>>> d
{'retrycount': 3, 42: 'douglas'}
Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed
Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
3.1.3 Deleting Items From Dictionaries
examples:
>>> d
{'retrycount': 3, 42: 'douglas'}
>>> del d[42]
>>> d
{'retrycount': 3}
>>> d.clear()
>>> d
{}
del lets you delete individual items from a dictionary by key.
clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.
3.2 Introducing Lists
Lists are Python's workhorse datatype.A list in Python is much more than an array in Java.A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.
3.2.1 Defining Lists
examples:
>>> li = ["a","b","mpilgrim","zt","hha"]
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[0]
'a'
>>> li[4]
'hha'
First, you define a list of five elements. Note that they retain their original order. This is not an accident. A list is an ordered set of elements enclosed in square brackets.
A list can be used like a zero-based array. The first element of any non-empty list is always li[0].
Negative List Indices
indice n. 指数;标记体 string indice: 字符串索引
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[-1]
'hha'
>>> li[-3]
'mpilgrim'
A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1].
Slicing a List
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[1:3]
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'zt']
>>> li[0:2]
['a', 'b']
You can get a subset of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index (in this case li[1]), up to but not including the second slice index (in this case li[3]).
Slicing works if one or both of the slice indices is negative. If it helps, you can think of it this way: reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don't want. The return value is everything in between.
Lists are zero-based, so li[0:3] returns the first three elements of the list, starting at li[0], up to but not including li[3].
Slicing Shorthand shorthand ['ʃɔ:thænd] n. 速记;速记法
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:]
['zt', 'hha']
>>> li[:]
['a', 'b', 'mpilgrim', 'zt', 'hha']
If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3]
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements
Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.
If both slice indices are left out, all elements of the list are included. But this is not the same as the original li list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy of a list.
3.2.2 Adding Elements to Lists
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.insert(2,"new2")
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.extend(["two","elements"])
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new', 'two', 'elements']
append adds a single element to the end of the list.
insert inserts a single element into a list. The numeric argument is the index of the first element that gets bumped out of position. Note that list elements do not need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one argument, a list. In this case, that list has two elements.
The Difference between extend and append
examples:
>>> li = ["a","b","c"]
>>> li.extend(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)
6
>>> li[-1]
'f'
>>> li.append(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> len(li)
7
>>> li[-1]
['d', 'e', 'f']
Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.
On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.
3.2.3 Searching Lists
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.index("b")
1
>>> li.index("f")
5
>>> li.index("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> "test" in li
False
index finds the first occurrence of a value in the list and returns the index.
If the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index. While this may seem annoying, it is a good thing, because it means your program will crash at the source of the problem, rather than later on when you try to use the invalid index.
To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.
3.2.4 Deleting List Elements
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("b")
>>> li
['a', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> li.pop()
['d', 'e', 'f']
>>> li
['a', 'c', 'd', 'e', 'f']
remove removes the first occurrence of a value from a list.
If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.
pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.
3.2.5 Usinig List Operators
examples:
>>> li = ["a","b",'mpigra']
>>> li = li + ['example','new']
>>> li
['a', 'b', 'mpigra', 'example', 'new']
>>> li +=['two']
>>> li
['a', 'b', 'mpigra', 'example', 'new', 'two']
>>> li = [1,2]*3
>>> li
[1, 2, 1, 2, 1, 2]
Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.
The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.
英文书地址
http://diveintopython3.org/
下载得到PDF版本
http://diveintopython3.org/d/diveintopython3-pdf-r860-2010-01-13.zip
解开压缩得到文件diveintopython3-r860.pdf和很多example.
python本身的官方文档
http://docs.python.org/3.1/
以上是版本python3,后来再使用中发现google app engine和django都还没有支持到python3,所以我本机安装的python2.6.4,所以决定先从小版本看起。
英文书地址:
http://diveintopython.org/toc/index.html
chapter 1. Installing Python
1.1 介绍了两种方式下载python
1如果要最新版本,请下载官方版本,下载地址:http://www.python.org/
得到文件python-2.6.4.msi,双击安装
2比较实用,笔者推荐activePython,下载地址:http://www.activestate.com/activepython/downloads/
得到文件ActivePython-2.6.4.10-win32-x86.msi,双击安装
1.2 The Interactive Shell
An interactive shell can evaluate arbitrary statements and expressions.This is extremely useful for debugging,quick hacking and testing.
chapter 2.Your First Python Program
odbchelper.py in examples:
def buildConnectionString(params):
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret"
}
print buildConnectionString(myParams)
the output of odbchelper.py will look like this:
pwd=secret;database=master;uid=sa;server=mpilgrim
2.2 Declaring Function
def buildConnectionString(params):
python do not specify the type about return value and arguments.
2.2.2 How Python's Datatypes Compare to Other Programming Languages
statically typed language
A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages.
dynamically typed language
A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value.
strongly typed language
A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it.
weakly typed language
A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion.
2.3.Documenting Functions
def buildConnectString(params):
""" Build a connection string from a dictionary of parameters.
Return string """
Python gives you an added incentive: the doc string is available at runtime as an attribute of the function.
2.4 Everything Is an Object
I type follow commands in my interactive shell:
>>> import odbchelper
>>> params = {"tt1":"tt1"}
>>> print odbchelper.buildConnectionString(params)
tt1=tt1
>>> print odbchelper.buildConnectionString.__doc__
Build a connection string from a dictionary
Returns string.
2.4.1 The Import Search Path:
>>> import sys
>>> sys.path
['', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\setuptools-0.6c11-py2.6.egg-info', 'E:\\book\\opensource\\python\\diveintopython-5.4\\py']
You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.
2.4.2 What's an Object
All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code.
everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
2.5 Indenting Code indent [in'dent, 'indent] n. 凹痕;订货单;契约;缩进 vt. 缩排
Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords.
bracket ['brækit] n. 支架;括号;墙上凸出的托架
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks.
2.6 Testing Modules
Modules are objects, and all modules have a built-in attribute __name__ and __doc__.
Chapter 3 . Native Datatypes
3.1 Introducing Dictionaries
One of Python's built-in datatypes is the dictionary, which defines one-to-one relationships between keys and values.
A dictionary in Python is like an instance of the Hashtable class in Java.
3.1.1. Defining Dictionaries
example:
>>> d = {"server":"mpilogrim","database":"master"}
>>> d
{'database': 'master', 'server': 'mpilogrim'}
>>> d["server"]
'mpilogrim'
>>> d["database"]
'master'
>>> d["ccc"]
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
KeyError: 'ccc'
the whole set of elements is enclosed in curly braces.And you can get values by key, but you can't get keys by value.
3.1.2 Modifying Dictionaries
>>> d["database"] = "pubs"
>>> d
{'database': 'pubs', 'server': 'mpilogrim'}
>>> d["uid"] = "sillycat"
>>> d
{'database': 'pubs', 'uid': 'sillycat', 'server': 'mpilogrim'}
You can not have duplicate keys in a dictionary. Assigning a value to an existing key will wipe out the old value.
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are “out of order”; When working with dictionaries, you need to be aware that dictionary keys are case-sensitive.
examples:
>>> d["key"] = "other value"
>>> d
{'key': 'other value'}
>>> d["Key"] = "third value"
>>> d
{'Key': 'third value', 'key': 'other value'}
examples:
>>> d = {}
>>> d
{}
>>> d["retrycount"] = 3
>>> d
{'retrycount': 3}
>>> d[42] = "douglas"
>>> d
{'retrycount': 3, 42: 'douglas'}
Dictionaries aren't just for strings. Dictionary values can be any datatype, including strings, integers, objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed
Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
3.1.3 Deleting Items From Dictionaries
examples:
>>> d
{'retrycount': 3, 42: 'douglas'}
>>> del d[42]
>>> d
{'retrycount': 3}
>>> d.clear()
>>> d
{}
del lets you delete individual items from a dictionary by key.
clear deletes all items from a dictionary. Note that the set of empty curly braces signifies a dictionary without any items.
3.2 Introducing Lists
Lists are Python's workhorse datatype.A list in Python is much more than an array in Java.A better analogy would be to the ArrayList class, which can hold arbitrary objects and can expand dynamically as new items are added.
3.2.1 Defining Lists
examples:
>>> li = ["a","b","mpilgrim","zt","hha"]
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[0]
'a'
>>> li[4]
'hha'
First, you define a list of five elements. Note that they retain their original order. This is not an accident. A list is an ordered set of elements enclosed in square brackets.
A list can be used like a zero-based array. The first element of any non-empty list is always li[0].
Negative List Indices
indice n. 指数;标记体 string indice: 字符串索引
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[-1]
'hha'
>>> li[-3]
'mpilgrim'
A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1].
Slicing a List
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[1:3]
['b', 'mpilgrim']
>>> li[1:-1]
['b', 'mpilgrim', 'zt']
>>> li[0:2]
['a', 'b']
You can get a subset of a list, called a “slice”, by specifying two indices. The return value is a new list containing all the elements of the list, in order, starting with the first slice index (in this case li[1]), up to but not including the second slice index (in this case li[3]).
Slicing works if one or both of the slice indices is negative. If it helps, you can think of it this way: reading the list from left to right, the first slice index specifies the first element you want, and the second slice index specifies the first element you don't want. The return value is everything in between.
Lists are zero-based, so li[0:3] returns the first three elements of the list, starting at li[0], up to but not including li[3].
Slicing Shorthand shorthand ['ʃɔ:thænd] n. 速记;速记法
examples:
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:]
['zt', 'hha']
>>> li[:]
['a', 'b', 'mpilgrim', 'zt', 'hha']
If the left slice index is 0, you can leave it out, and 0 is implied. So li[:3] is the same as li[0:3]
Similarly, if the right slice index is the length of the list, you can leave it out. So li[3:] is the same as li[3:5], because this list has five elements
Note the symmetry here. In this five-element list, li[:3] returns the first 3 elements, and li[3:] returns the last two elements. In fact, li[:n] will always return the first n elements, and li[n:] will return the rest, regardless of the length of the list.
If both slice indices are left out, all elements of the list are included. But this is not the same as the original li list; it is a new list that happens to have all the same elements. li[:] is shorthand for making a complete copy of a list.
3.2.2 Adding Elements to Lists
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.insert(2,"new2")
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new']
>>> li.extend(["two","elements"])
>>> li
['a', 'b', 'new2', 'mpilgrim', 'zt', 'hha', 'new', 'two', 'elements']
append adds a single element to the end of the list.
insert inserts a single element into a list. The numeric argument is the index of the first element that gets bumped out of position. Note that list elements do not need to be unique; there are now two separate elements with the value 'new', li[2] and li[6].
extend concatenates lists. Note that you do not call extend with multiple arguments; you call it with one argument, a list. In this case, that list has two elements.
The Difference between extend and append
examples:
>>> li = ["a","b","c"]
>>> li.extend(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f']
>>> len(li)
6
>>> li[-1]
'f'
>>> li.append(["d","e","f"])
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> len(li)
7
>>> li[-1]
['d', 'e', 'f']
Lists have two methods, extend and append, that look like they do the same thing, but are in fact completely different. extend takes a single argument, which is always a list, and adds each of the elements of that list to the original list.
On the other hand, append takes one argument, which can be any data type, and simply adds it to the end of the list. Here, you're calling the append method with a single argument, which is a list of three elements.
3.2.3 Searching Lists
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.index("b")
1
>>> li.index("f")
5
>>> li.index("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> "test" in li
False
index finds the first occurrence of a value in the list and returns the index.
If the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index. While this may seem annoying, it is a good thing, because it means your program will crash at the source of the problem, rather than later on when you try to use the invalid index.
To test whether a value is in the list, use in, which returns True if the value is found or False if it is not.
3.2.4 Deleting List Elements
examples:
>>> li
['a', 'b', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("b")
>>> li
['a', 'c', 'd', 'e', 'f', ['d', 'e', 'f']]
>>> li.remove("test")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> li.pop()
['d', 'e', 'f']
>>> li
['a', 'c', 'd', 'e', 'f']
remove removes the first occurrence of a value from a list.
If the value is not found in the list, Python raises an exception. This mirrors the behavior of the index method.
pop is an interesting beast. It does two things: it removes the last element of the list, and it returns the value that it removed. Note that this is different from li[-1], which returns a value but does not change the list, and different from li.remove(value), which changes the list but does not return a value.
3.2.5 Usinig List Operators
examples:
>>> li = ["a","b",'mpigra']
>>> li = li + ['example','new']
>>> li
['a', 'b', 'mpigra', 'example', 'new']
>>> li +=['two']
>>> li
['a', 'b', 'mpigra', 'example', 'new', 'two']
>>> li = [1,2]*3
>>> li
[1, 2, 1, 2, 1, 2]
Lists can also be concatenated with the + operator. list = list + otherlist has the same result as list.extend(otherlist). But the + operator returns a new (concatenated) list as a value, whereas extend only alters an existing list. This means that extend is faster, especially for large lists.
The * operator works on lists as a repeater. li = [1, 2] * 3 is equivalent to li = [1, 2] + [1, 2] + [1, 2], which concatenates the three lists into one.
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 434NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 297Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 380Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 341Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 422NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 368Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 296Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 214GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 396GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 282GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 269Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 268Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 256Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 243Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 240NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 229Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 526NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 232Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 324Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 323Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
dive into python3 (中文版)dive into python3 (中文版)dive into python3 (中文版)
Dive into Python 中文版 Dive into Python 中文版
《深入Python 3》(Dive Into Python 3,英,)的的电子版,HTML格式
Dive into Python3 很不错哦,有中文的就更好了。
diveintopython源代码 很全
dive into python_代码_教程 dive into python_代码_教程
diveintopython3 书中源代码,非常好的一本书,极力推介,本人从中学到很多写代码的技巧
深入python,深入Python (Dive Into Python) 译者序 by limodou 主页(http://phprecord.126.com) Python论坛 本书英文名字为《Dive Into Python》,其发布遵守 GNU 的自由文档许可证(Free Document Lience)的...
dive into python的中文版,很不错的python教程
dive into python英文原版,Dive Into Python 3 covers Python 3 and its differences from Python 2. Compared to Dive Into Python, it’s about 20% revised and 80% new material. The book is now complete, ...
Dive Into Python 2 中文版 深入学习Python,需要学习Python基础知识
Dive Into Python 3 中文版.pdf 如果需要英文的也可以联系我
dive into python 3 英文版,很好懂,用具体例子讲述Python语法和一些编程技巧
Dive Into Python 3 examples,随书示例代码包。
Dive Into Python 3 中文版
Dive Into Python 3 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
《Dive Into Python》,带完整目录书签,经典文档,供参考。
Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyit onpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthat istrue,you’dbebetteroffstartingatthebeginning.) Python3...
Dive Into Python 中文译文版 带帮助文档和全套源码