原文链接:http://composingprograms.com/pages/23-sequences.html
What is sequences?
A sequence is an ordered collection of values.
It is a collection of behaviors that are shared among several different types of data.
Three basic sequence types: lists, tuples, range objects.
Two properties :
Length. A sequence has a finite length. An empty sequence has length 0.
Element selection. A sequence has an element corresponding to any non-negative integer index less than its length, starting at 0 for the first element.
Common Sequence Operations
官方文档:https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
Noted
1) repetition operations (*)
Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times.
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
To solve this problem:
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
2) Concatenating immutable sequences always results in a new object.
3) Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition.
4) index raises ValueError when x is not found in s.
Sequence Types
There are Immutable Sequence Types and Mutable Sequence Types.
Immutable Sequence support for the hash() built-in but Mutable Sequence not, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s.
![]()
(1) t must have the same length as the slice it is replacing.
(2) The optional argument i defaults to -1, so that by default the last item is removed and returned.
(3) remove raises ValueError when x is not found in s.
(4) The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.
(5) clear() and copy() are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as dict and set)
(6) The value n is an integer, or an object implementing index(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.
Lists
Lists are mutable sequences, typically used to store collections of homogeneous items, lists have arbitrary length.
it has a large set of built-in behaviors, along with specific syntax to express those behaviors.
Lists may be constructed in several ways:
- Using a pair of square brackets to denote the empty list: []
- Using square brackets, separating items with commas: [a], [a, b, c]
- Using a list comprehension: [x for x in iterable]
- Using the type constructor:list() or list(iterable)
Sequence Iteration
The for statement
The while loop
def count(s, value):
"""this function is used to count the occurrences of ''value'' in 's' """
total, index = 0, 0
while index < len(s):
if s[index] == value:
total = total + 1
index = index + 1
return total
if "__name__ " == "__main__":
digits = [1, 2, 3, 4, 5, 6, 1]
result = count(digits, 1)
print(result)
Sequence unpacking
This pattern of binding multiple names to multiple values in a fixed-length sequence is called sequence unpacking.
>>> pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]
>>> same_count = 0
>>> for x, y in pairs:
if x == y:
same_count = same_count + 1
>>> same_count
2
range
range represents a range of integers.
>>> range(1, 10) # Includes 1, but not 10
range(1, 10)
>>> list(range(5, 8))
[5, 6, 7]
>>> list(range(4))
[0, 1, 2, 3]
Sequence Processing
List Comprehensions
>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]
to select a subset of values that satisfy some condition
>>> [x for x in odds if 25 % x == 0]
[1, 5]
The general form of a list comprehension is:
[<map expression> for <name> in <sequence expression> if <filter expression>]
To evaluate a list comprehension, Python evaluates the <sequence expression>, which must return an iterable value. Then, for each element in order, the element value is bound to <name>, the filter expression is evaluated, and if it yields a true value, the map expression is evaluated. The values of the map expression are collected into a list.
Aggregation
to aggregate all values in a sequence into a single value, such as sum, min, and max.
>>> def divisors(n):
return [1] + [x for x in range(2, n) if n % x == 0]
>>> divisors(4)
[1, 2]
>>> divisors(12)
[1, 2, 3, 4, 6]
Higher-Order Functions
def divisors_of(n):
divides_n = lambda x: n % x == 0
return [1] + keep_if(divides_n, range(2, n))
def keep_if(filter_fn, s):
return [x for x in s if filter_fn(x)]
divisors_of(12)
String
it quiet similar to above sequence.
More reading material..
Trees
This will give a specific note.
Linked Lists
Define a linked list :
link is a constructor and first and rest are selectors for an abstract data representation of linked lists.
>>> empty = 'empty'
>>> def is_link(s):
"""s is a linked list if it is empty or a (first, rest) pair."""
return s == empty or (len(s) == 2 and is_link(s[1]))
>>> def link(first, rest):
"""Construct a linked list from its first element and the rest."""
assert is_link(rest), "rest must be a linked list."
return [first, rest]
>>> def first(s):
"""Return the first element of a linked list s."""
assert is_link(s), "first only applies to linked lists."
assert s != empty, "empty linked list has no first element."
return s[0]
>>> def rest(s):
"""Return the rest of the elements of a linked list s."""
assert is_link(s), "rest only applies to linked lists."
assert s != empty, "empty linked list has no rest."
return s[1]
>>> four = link(1, link(2, link(3, link(4, empty))))
>>> first(four)
1
>>> rest(four)
[2, [3, [4, 'empty']]]
operation: length and element selection
>>> def len_link(s):
"""Return the length of linked list s."""
length = 0
while s != empty:
s, length = rest(s), length + 1
return length
>>> def getitem_link(s, i):
"""Return the element at index i of linked list s."""
while i > 0:
s, i = rest(s), i - 1
return first(s)
>>> len_link(four)
4
>>> getitem_link(four, 1)
2