python Basic Learning Notes 2 (Deep List, Tuple Sequence, Set, Dictionary, Circulation Skills, Conditional Control, Sequence Comparison)

Posted by Dan06 on Fri, 06 Sep 2019 06:01:08 +0200

data structure

Deep List

function

There are many ways to list data types, as shown in the following table

list.append(x)

Add an item at the end. It's equivalent to a [len (a):]= [x].  

list.extend(iterable)

Expand the list through all items in the traversal. Equivalent to a[len(a):] = iterable.  

list.insert(i, x)

Insert an item at a given location. The index of the i-bit insertion position so a.insert(0, x) will be inserted at the front, and a.insert(len(a), x) is equivalent to a.append(x)  

list.remove(x)

Delete items with a value of x in the list  

list.pop([i])

Delete the item at the specified location and return it. If no index a.pop() is specified, the last item is deleted. ([] Represents i as an optional parameter, not to enter it)  

list.clear()

Delete all items in the list. Equivalent to del a [:]  

list.index(x[, start[, end]])

Returns the item index with the first value x. start and end indicate that only items within this interval are found.  

list.count(x)

Number of times the value x appears in the return list  

list.sort(key=None, reverse=False)

List sorting. key sort keyword, reverse is inverted  

list.reverse()

Place the elements in the list backwards.  

list.copy()

Returns a shallow copy of the list. Equivalent to a [:]  

List Stack

We can use lists as stacks, for example

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())

# Result:
# [3, 4, 5, 6, 7]
# 7
# 6
# 5
# 4

List queue

We can use lists as queues, for example

Ordinary lists add and subtract items quickly from the end, but when adding and subtracting items from the top, all items move forward one bit, which is inefficient.

So we use collections.deque To achieve the queue, it can quickly add and subtract data at both ends.

from collections import deque

queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")
queue.append("Graham")
print(queue)
print(queue.popleft())
print(queue.popleft())

List parsing

List parsing is a way of generating lists through a circular expression.

Cyclic expression is mainly composed of two parts: the first half is the formula and the second half is the cyclic control. for example

squares = [x**2 for x in range(10)]

Amount to

squares = []
for x in range(10):
    squares.append(x ** 2)
print(squares)

Multiple loops and judgments may exist in complex situations

squares = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]

Amount to

squares = []
for x in [1, 2, 3]:
    for y in [3, 1, 4]:
        if x != y:
            squares.append((x, y))

Nested list parsing

List parsing can be an arbitrary expression, including another list parsing expression

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
transposed = [[row[i] for row in matrix] for i in range(4)]

Amount to

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])

It's also equivalent to

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
transposed = []
for i in range(4):
    transposed_row = []
    for row in matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)

This example can also use built-in functions to get results more easily.

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]
transposed = list(zip(*matrix))

Delete statement

We can use del to delete data from the list

    array = [-1, 1, 66.25, 333, 333, 1234.5]
    del array[0]
    print(array) # Results [1, 66.25, 333, 333, 1234.5]
    del array[2:4]
    print(array) # Results [1, 66.25, 1234.5]
    del array[:]
    print(array) # Results []
    del array
    # print(array)  # Results Unbound LocalError: local variable'a'reference before assignment

Tuples and Sequences

Tuples are composed of several comma-separated values

tuple1 = 12345, 54321, 'hello!'
print(tuple1[0])  # Results 12345
print(tuple1)  # Results (12345, 54321,'hello!')

# Yuan Zu can be nested
unit = tuple1, (1, 2, 3, 4, 5)
print(unit)  # Results ((12345, 54321,'hello!'), (1, 2, 3, 4, 5))

# Tuples are immutable
# tuple1[0] = 88888 # Error reporting TypeError:'tuple'object does not support item assignment

# Tuples can contain variable objects
tuple2 = [1, 2, 3], [3, 2, 1]
tuple2[0][0] = 3
print(tuple2)  # Results ([3, 2, 3], [3, 2, 1])

An empty tuple is represented by a pair of parentheses

empty = ()
print(empty) # Results ()

We can use sequence decompression to assign meta-ancestors to multiple variables (the number of variables is the same as the number of tuple contents)

compress = 12345, 54321, 'hello!'
first, second, third = compress
print(first)
print(second)
print(third)
# Results 12345
#      54321
#      hello!

aggregate

Similar to java is a collection that does not need to be repeated.

set() functions, not {}, must be used when creating collections. {} is used to create an empty dictionary.

# Duplicate entries will be deleted
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  # Results {apple','orange','pear','banana'}

# Determine whether or not in a set
print('orange' in basket)  # Result True
print('crabgrass' in basket)  # Results False

# Operation of Letter Sets
set1 = set('abracadabra')
set2 = set('alacazam')
print(set1)  # Results {a','d','b','r','c'}
print(set2)  # Results {z','a','l','m','c'}
print(set1 - set2)  # Results {d','b','r'}
print(set1 | set2)  # Results {z','a','l','m','d','b','r','c'}
print(set1 & set2)  # Results {a','c'}
print(set1 ^ set2)  # Results {z','r','d','b','l','m'}

Sets also support expression parsing

# Analytic expression
set3 = {x ** 2 for x in range(10)}
print(set3)  # Results {z','r','d','b','l','m'}

Dictionaries

A dictionary is a set of key-value pairs, and the keys are unique in a unified dictionary. Create a new empty dictionary using {}

    # Create an empty dictionary
    tel = {}
    print(tel)  # Result {}

    # Adding elements
    tel['second'] = 2
    tel['first'] = 1
    print(tel)  # Results {second': 2,'first': 1}

    # Modify element values
    tel['first'] = 100
    print(tel)  # Results {second': 2,'first': 100}

    # Get element values
    print(tel['second'])  # Result 2

    # Get all the keys in the dictionary
    print(list(tel))  # Results ['second','first']

    # Sort dictionary keys
    print(sorted(tel))  # Results ['first','second']

    # Check whether the element exists
    print('first' in tel)  # Result True

    # Is there no procuratorial element?
    print('first' not in tel)  # Results False

    # Delete elements
    del tel['second']
    print(tel)  # Result {first': 100}

dict() functions can create dictionaries directly from key-value pair sequences

    print(dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]))
    # Results {Sape': 4139,'guido': 4127,'jack': 4098}

Dictionaries can also be created by expression parsing

    print({x: x ** 2 for x in (2, 4, 6)})
    # Results {2:4, 4:16, 6:36}

Cyclic Skills

When retrieving a dictionary, you can use the items() function to retrieve keys and values at the same time.

    knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    for k, v in knights.items():
        print(k + ":" + v)
    # Results gallahad:the pure
    #      robin:the brave

The enumerate() function can be used to traverse the sequence, and locations and values can be retrieved at the same time.

    for i, v in enumerate(['tic', 'tac', 'toe']):
        print(i, v)
    # Result 0 tic
    #      1 tac
    #      2 toe

You can use zip() function to pair two or more sequences at the same time.

    questions = ['name', 'quest', 'favorite color']
    answers = ['lancelot', 'the holy grail', 'blue']
    for q, a in zip(questions, answers):
        print('What is your {0}?  It is {1}.'.format(q, a))
    # What is your name? It is lancelot.
    #       What is your quest?  It is the holy grail.
    #       What is your favorite color?  It is blue.

reversed() functions can be used to reverse cyclic sequences

    questions = ['name', 'quest', 'favorite color']
    for q in questions:
        print(q)
    for q in reversed(questions):
        print(q)
    # Result name
    #       quest
    #       favorite color
    #       favorite color
    #       quest
    #       name

The sorted() function is used to sort the cyclic sequence. This function returns a new sort sequence without affecting the original sequence.

    questions = ['name', 'quest', 'favorite color']
    for q in sorted(questions):
        print(q)
    for q in questions:
        print(q)
    # Result favorite color
    #       name
    #       quest
    #       name
    #       quest
    #       favorite color

Sometimes you may want to modify the contents of a list during a loop. Generally speaking, it's easier and safer to create a new list instead.

    raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
    filtered_data = []
    for value in raw_data:
        if not math.isnan(value):
            filtered_data.append(value)
    print(filtered_data)
    # Results [56.2, 51.7, 55.3, 52.5, 47.8]

Deep conditional control

Any operation can be used in the while and if conditionals, not just the comparison operation.

in Check whether a value is in a sequence.
    array1 = [1, 3, 5, 7, 9]
    if 1 in array1:
        print("1 in array1 = true")
    if 2 in array1:
        print("2 in array1 = true")
    # Result 1 in array1 = true
not in Check whether a value is not in a sequence.
    array1 = [1, 3, 5, 7, 9]
    if 1 not in array1:
        print("1 not in array1 = true")
    if 2 not in array1:
        print("2 not in array1 = true")
    # Results 2 not in array1 = true
is Comparing two objects is the same object.
    array1 = [1, 3, 5, 7, 9]
    array2 = array1
    array3 = [1, 3, 5, 7, 9]
    if array1 is array2:
        print("array1 is array2 = true")
    if array1 is array3:
        print("array1 is array3 = true")
    # Results array1 is array2 = true
 is not Comparing two objects is not the same object.
    array1 = [1, 3, 5, 7, 9]
    array2 = array1
    array3 = [1, 3, 5, 7, 9]
    if array1 is not array2:
        print("array1 is not array2 = true")
    if array1 is not array3:
        print("array1 is not array3 = true")
    # Results array1 is not array3 = true
and and operation
    if a < b and b > c:
        print("a < b and b > c = true")
or Or operation
    if a < b or b > c:
        print("a < b or b > c = true")
not Non-operation
    if not b > c:
        print("a < b and b > c = true")

Comparison of Sequences with Other Types

Sequences can be compared with other types of sequences.

The comparison rule is to compare the first item first, and if the same, continue to compare backwards until a sequence is exhausted.

    print((1, 2, 3) < (1, 2, 4))  # Result True
    print([1, 2, 3] < [1, 2, 4])  # Result True
    print('ABC' < 'C' < 'Pascal' < 'Python')  # Result True
    print((1, 2, 3, 4) < (1, 2, 4))  # Result True
    print((1, 2) < (1, 2, -1))  # Result True
    print((1, 2, 3) == (1.0, 2.0, 3.0))  # Result True
    print((1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4))  # Result True

Topics: Programming Java Python