您的位置:首页 > 编程语言 > Python开发

Python3基础进阶(二)

2017-05-29 11:57 381 查看

Chapter 3. Py Filling: Lists, Tuples, Dictionaries, and Sets

In Chapter 2 we started at the bottom with Python’s basic data types: booleans, integers, floats, and strings. If you think of those as atoms, the data structures in this chapter are like molecules.

Lists and Tuples

Most computer languages can represent a sequence of items indexed by their integer position: first, second, and so on down to the last. You’ve already seen Python strings, which are sequences of characters. You’ve also had a little preview of lists, which you’ll now see are sequences of anything.

Python has two other sequence structures: tuples and lists. These contain zero or more elements. Unlike strings, the elements can be of different types. In fact, each element can be any Python object.

Why does Python contain both lists and tuples? Tuples are immutable; when you assign elements to a tuple, they can’t be changed. Lists are mutable, meaning you can insert and delete elements with great enthusiasm.

Lists

Lists are good for keeping track of things by their order, especially when the order and contents might change. Unlike strings, lists are mutable. You can change a list in-place, add new elements, and delete or overwrite existing elements. The same value can occur more than once in a list.

Create with [] or
list()

A list is made from zero or more elements, separated by commas, and surrounded by square brackets; You can also make an empty list with the
list()
function:

>>> empty_list = []
>>> empty_list
[]
>>> weekdays = ['Monday', 'Friday']
>>> weekdays
['Monday', 'Friday']
>>> another_empty_list = []
>>> another_empty_list
[]


If you only want to keep track of unique values and don’t care about order, a Python set might be a better choice than a list.

Convert Other Data Types to Lists with list()

Python’s
list()
function converts other data types to lists. The following example converts a string to a list of one-character strings:

>>> list('cat')
['c', 'a', 't']


This example converts a tuple to a list:

>>> a_tuple = ('a', 'b')
>>> list(a_tuple)
['a', 'b']


Using
split()
to chop a string into a list by some separator string:

>>> a_string = 'C/h/i/n/a'
>>> a_string.split('/')
['C', 'h', 'i', 'n', 'a']


What if you have more than one separator string in a row in your original string? Well, you get an empty string as a list item:

>>> a_string = 'C/h//i/n//a'
>>> a_string.split('/')
['C', 'h', '', 'i', 'n', '', 'a']


Get an Item by Using [ offset ]

You can extract a single value from a list by specifying its offset:

>>> a_list = ['a', 'b', 'c']
>>> a_list[0]
'a'
>>> a_list[-2]
'b'
>>> a_list[4]
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
a_list[4]
IndexError: list index out of range


Lists of Lists

Lists can contain elements of different types, including other lists, as illustrated here:

>>> list1 = ['C']
>>> list2 = ['h']
>>> list3 = [list1, list2, 'ina', 1]
>>> list3
[['C'], ['h'], 'ina', 1]
>>> list3[1][0]
'h'


Change an Item by [ offset ]

>>> a_list = ['C', 'a', 'h']
>>> a_list[1] = 'b'
>>> a_list
['C', 'b', 'h']


You can’t change a character in a string in this way, because strings are immutable. Lists are mutable.

Get a Slice to Extract Items by Offset Range

You can extract a subsequence of a list by using a slice; and the trick to reverse a list:

>>> a_list = ['a', 's', 'd']
>>> a_list[::2]
['a', 'd']
>>> a_list[::-1]
['d', 's', 'a']


Add an Item to the End with append()

>>> a_list = ['a', 's', 'd']
>>> a_list.append('f')
>>> a_list
['a', 's', 'd', 'f']


Combine Lists by Using extend() or +=

You can merge one list into another by using extend(). Alternatively, you can use +=:

>>> list1 = ['C']
>>> list2 = ['s']
>>> list1.extend(list2)
>>> list1
['C', 's']
>>> list2 += list1
>>> list2
['s', 'C', 's']


If we had used
append()
, others would have been added as a single list item rather than merging its items:

>>> list1 = ['C']
>>> list2 = ['s']
>>> list1.append(list2)
>>> list1
['C', ['s']]


Add an Item by Offset with insert()

When you want to add an item before any offset in the list, use insert().

>>> a_list = ['a', 'd', 'f']
>>> a_list.insert(1, 's')
>>> a_list
['a', 's', 'd', 'f']
>>> a_list.insert(100, 'q')
>>> a_list
['a', 's', 'd', 'f', 'q']


Delete an Item by Offset with del

del
is a Python statement, not a list method—you don’t say marxes[-2].del(). It’s sort of the reverse of assignment (=): it detaches a name from a Python object and can free up the object’s memory if that name was the last reference to it.

Delete an Item by Value with remove()

Get an Item by Offset and Delete It by Using pop()

You can get an item from a list and delete it from the list at the same time by using
pop()
. If you call
pop()
with an offset, it will return the item at that offset; with no argument, it uses -1. So, pop(0) returns the head(start) of the list, and pop() or pop(-1) returns the tail (end).

If you use
append()
to add new items to the end and
pop()
to remove them from the same end, you’ve implemented a data structure known as a LIFO (last in, first out) queue. This is more commonly known as a stack. pop(0) would create a FIFO (first in, first out) queue. These are useful when you want to collect data as they arrive and work with either the oldest first (FIFO) or the newest first (LIFO).

Find an Item’s Offset by Value with index()

If you want to know the offset of an item in a list by its value, use
index()
:

>>> a_list = ['a', 'b', 'c']
>>> a_list.index('b')
1


Test for a Value with in

>>> a_list = ['a', 'b', 'c']
>>> 'd' in a_list
False


If you check for the existence of some value in a list often and don’t care about the order of items, a Python set is a more appropriate way to store and look up unique values.

Count Occurrences of a Value by Using count()

>>> a_list = ['a', 'b', 'c', 'c']
>>> a_list.count('c')
2


Convert to a String with join()

>>> a_list = ['a', 'b', 'c', 'c']
>>> '-'.join(a_list)
'a-b-c-c'


join()
is a string method, not a list method. You can’t say marxes.join(‘, ‘), even though it seems more intuitive. The argument to join() is a string or any iterable sequence of strings (including a list), and its output is a string.

If join() were just a list method, you couldn’t use it with other iterable objects such as tuples or strings. If you did want it to work with any iterable type, you’d need special code for each type to handle the actual joining. It might help to remember:
join()
is the opposite of
split()
.

>>> a_list = ['a', 'b', 'c']
>>> separator = '*'
>>> joined = separator.join(a_list)
>>> joined
'a*b*c'
>>> joined.split(separator)
['a', 'b', 'c']


Reorder Items with sort()

You’ll often need to sort the items in a list by their values rather than their offsets. Python provides two functions:

• The list function
sort()
sorts the list itself, in place.

• The general function
sorted()
returns a sorted copy of the list.

If the items in the list are numeric, they’re sorted by default in ascending numeric order. If they’re strings, they’re sorted in alphabetical order:

>>> a_list = ['b', 'c', 'a']
>>> sorted_list = sorted(a_list)
>>> sorted_list
['a', 'b', 'c']
>>> sorted_list[0] = 'q'
>>> sorted_list
['q', 'b', 'c']
>>> a_list    # sorted_marxes is a copy, and creating it did not change the original list
['b', 'c', 'a']


The default sort order is ascending, but you can add the argument reverse=True to set it to descending:

>>> list1 = [1, 3, 2, 9, 4.1]
>>> list1.sort()
>>> list1
[1, 2, 3, 4.1, 9]
>>> list1.sort(reverse=True)
>>> list1
[9, 4.1, 3, 2, 1]


Get Length by Using len()

Assign with =, Copy with copy()

>>> list1 = ['1', '2', '3']
>>> list2 = list1
>>> list1[0] = 'number'
>>> list1
['number', '2', '3']
>>> list2
['number', '2', '3']
>>> list2[1] = 'is'
>>> list2
['number', 'is', '3']
>>> list1
['number', 'is', '3']


You can copy the values of a list to an independent, fresh list by using any of these methods:

• The list
copy()
function

• The
list()
conversion function

• The list
slice [:]


>>> a = [1, 2, 3]
>>> b = a.copy()
>>> c = list(a)
>>> d = a[:]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]


b, c, and d are copies of a: they are new objects with their own values and no connection to the original list object [1, 2, 3] to which a refers. Changing a does not affect the copies b, c, and d:

>>> a[0] = 'qq'
>>> a
['qq', 2, 3]
>>> b
[1, 2, 3]
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]


Tuples

Similar to lists, tuples are sequences of arbitrary items. Unlike lists, tuples are immutable, meaning you can’t add, delete, or change items after the tuple is defined. So, a tuple is similar to a constant list.

Create a Tuple by Using ()

Making an empty tuple using ():

>>> empty_tuple = ()
>>> empty_tuple
()
>>> type(empty_tuple)
<class 'tuple'>


To make a tuple with one or more elements, follow each element with a comma. This works for one-element tuples:

>>> one_tuple = 'a,'
>>> one_tuple
'a,'
>>> type(one_tuple)
<class 'str'>
>>>
>>> one_tuple = 'a',
>>> one_tuple
('a',)


If you have more than one element, follow all with a comma but the last one :

>>> tuple1 = 'q', 'q'
>>> tuple1
('q', 'q')
>>> type(tuple)
<class 'type'>


Python includes parentheses when echoing a tuple. You don’t need them—it’s the trailing commas that really define a tuple—but using parentheses doesn’t hurt. You can use them to enclose the values, which helps to make the tuple more visible:

>>> tuple1 = ('q', 'q')
>>> tuple1
('q', 'q')


Tuples let you assign multiple variables at once: tuple unpacking

>>> tuple1 = ('q', 'Q')
>>> a, b = tuple1
>>> a
'q'
>>> b
'Q'


This is sometimes called tuple unpacking.

You can use tuples to exchange values in one statement without using a temporary variable:

>>> a = 'q'
>>> b = 'Q'
>>> a, b = b, a
>>> a
'Q'
>>> b
'q'


The
tuple()
conversion function makes tuples from other things:

>>> a = [1, 2, 3]
>>> tuple(a)
(1, 2, 3)


Tuples versus Lists

You can often use tuples in place of lists, but they have many fewer functions—there is no append(), insert(), and so on—because they can’t be modified after creation. Why not just use lists instead of tuples everywhere?

• Tuples use less space.

• You can’t clobber tuple items by mistake.

• You can use tuples as dictionary keys .

• Named tuples can be a simple alternative to objects.

• Function arguments are passed as tuples.

Dictionaries

You specify a unique key to associate with each value. This key is often a string, but it can actually be any of Python’s immutable types: boolean, integer, float, tuple, string, and others. Dictionaries are mutable, so you can add, delete, and change their key-value elements.

Create with {}

To create a dictionary, you place curly brackets ({}) around comma-separated key : value pairs.

>>> empty_dic = {}
>>> empty_dic
{}
>>> dic1 = {'A':'a', 'B':'b', 'C':'c'}
>>> dic1
{'A': 'a', 'B': 'b', 'C': 'c'}


Convert by Using dict()

You can use the dict() function to convert two-value sequences into a dictionary.

>>> list1 = [['a','b'], ['c','d']]
>>> dict(list1)
{'a': 'b', 'c': 'd'}


Remember that the order of keys in a dictionary is arbitrary, and might differ depending on how you add items.

We could have used any sequence containing two-item sequences.

A list of two-item tuples; A list of two-character strings; A tuple of two-item lists; A tuple of two-character strings.

Add or Change an Item by [ key ]

Adding an item to a dictionary is easy. Just refer to the item by its key and assign a value.

>>> dic1 = {'A':'a', 'B':'b', 'C':'c'}
>>> dic1['D'] = 'd'
>>> dic1
{'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}


Remember that dictionary keys must be unique.

Combine Dictionaries with update()

>>> dic1 = {'A':'a', 'B':'b', 'C':'c'}
>>> dic2 = {'D':'d', 'E':'e'}
>>> dic1.update(dic2)
>>> dic1
{'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e'}


Delete an Item by Key with del

Delete All Items by Using clear()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python