List, Three Nets in One

Posted by arth on Mon, 09 Sep 2019 14:30:28 +0200

In python, a list is represented in square brackets, []
Within square brackets, it can be int, str-type data, or even Boolean values such as True/False.

a=[]        #A variable a is defined, which is list type and empty.
print(type(a))
print(bool(a))     #Use the built-in function bool() to see the Boolean value of a variable of list type, because it is empty, so it is False.
print(a)    #Print list type variable a

//Print results:
<class 'list'>
False
[]
a = ['2',3,'qiwsir.github.io']
print(['2', 3, 'qiwsir.github.io'])
print(type(a))
print(bool(a))
print(a)

//Print results:
['2', 3, 'qiwsir.github.io']
<class 'list'>
True
['2', 3, 'qiwsir.github.io']

Index and slice

a = ['2', 3, 'qiwsir.github.io']
print(a[0])    #The index number also starts at 0.
print(a[1])
print(a[:2])   #Similar to str, the range of slices is: Include the start position, before the end position
print(a[1:])
print(a[2][7:13]) #You can slice list elements twice, first select the string with index 2 subscripts, and then select the subscripts of 7 to 12 in the string.

//Print results
2
3
['2', 3]
[3, 'qiwsir.github.io']
github

Find index by element

lang = "python"
print(lang.index("y"))
lst = ['python','java','c++']
print(lst.index('java'))

//Print results
1
1

Start from the back

lang = "python"
lst = ['python','java','c++']
print(lang[-1])
print(lst[-1])

//Print results
n
c++

If you want to slice, you should pay attention to it. The slice of the sequence must have the number on the left less than the number on the right. The lang[-1:-3] does not obey this rule and returns an empty one.

lang = "python"
lst = ['python','java','c++']
print(lang[-1:-3])
print(lang[-3:-1])
print(lst[-3:-1])
//Print results
     # The front is empty.
ho
['python', 'java']

Reversal

alst = [1,2,3,4,5,6]
print(alst[::-1]) # inversion
print(alst)
Print results
[6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6]

The following functions can also be inverted

alst = [1,2,3,4,5,6]
print(list(reversed(alst)))
Print results
[6, 5, 4, 3, 2, 1]
print(list(reversed("abcd")))
//Print results
['d', 'c', 'b', 'a']

basic operation

  1. len()
  2. + To connect two sequences
  3. * Repetitive elements
  4. in
  5. max() and min()

Appnd adds elements to the end

a = ["good","python","I"]
print(a)
a.append("like")        #Add str type "like" to list
print(a)
a.append(100)           #Add int type 100 to list
print(a)
//Print results
['good', 'python', 'I']
['good', 'python', 'I', 'like']
['good', 'python', 'I', 'like', 100]

Extended merges two lists

la = [1, 2, 3]
lb = ['qiwsir', 'python']
la.extend(lb)
print(la)

//Print results
[1, 2, 3, 'qiwsir', 'python']

count looks at the number of occurrences of elements

la = [1,2,1,1,3]
print(la.count(1))
Print results
3

insert specifies the location to add elements

all_users = ['qiwsir', 'github', 'io']
print(all_users)

all_users.insert(0,"python")  # Add python at index 0
print(all_users)

//Print results
['qiwsir', 'github', 'io']
['python', 'qiwsir', 'github', 'io']

remove specified element deletion

lst = ["python","java","python","c"]
lst.remove("python")  # Specify element deletion, if the same, delete only the left
print(lst)
//Print results
['java', 'python', 'c']

pop() deletes the end by default, or you can specify index value deletion

all_users = ['qiwsir', 'github', 'io', 'algorithm']
all_users.pop()  # Delete the end by default without specifying parameters
print(all_users)
all_users.pop(0)  # Specified index deletion
print(all_users)
//Print results
['qiwsir', 'github', 'io']
['github', 'io']

reverse reverses the order of elements in the list

a = [3,5,1,6]
a.reverse()
print(a)
Print results
[6, 1, 5, 3]

Sort sorts sort lists from small to large

a = [6, 1, 5, 3]
a.sort()# Ranking from Small to Large
print(a)
Print results
[1, 3, 5, 6]

From big to small

a = [6, 1, 5, 3]
a.sort(reverse=True) # Ranking from large to small
print(a)
Print results
[6, 5, 3, 1]

Elements from fewer to more

lst = ["python","java","c","pascal","basic"]
lst.sort(key=len)  # Sort by string length from fewer to more
print(lst)
//Print results
['c', 'java', 'basic', 'python', 'pascal']

Multidimensional List
There can be multiple lists in a list

matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix[0][1]) # Index 0 is the list of elements 1, 2, 3. First index the list, the elements in the index list.
Print results
2

split() segmentation

line = "Hello.I am qiwsir.Welcome you."
print(line.split("."))    #Take English period as separator, get list
print(line.split(".",1))   #This 1, which means that only once is partitioned
name = "Albert Ainstain"    #It is also possible to use spaces as separators
print(name.split(" "))
//Print results
['Hello', 'I am qiwsir', 'Welcome you', '']
['Hello', 'I am qiwsir.Welcome you.']
['Albert', 'Ainstain']

Default all symbols and spaces without input parameters

s = "I am, writing\npython\tbook on line"   #This string has spaces, commas, newline n, tab indentation t symbols
print(s)         #Style after output
print(s.split())       #With split(), but no parameters are entered in parentheses, and all symbol spaces are split by default.
//Print results
I am, writing
python	book on line
['I', 'am,', 'writing', 'python', 'book', 'on', 'line']

join() splicing

name = ['Albert', 'Ainstain']
print(name)  # Print the original text
print("".join(name))  # Splicing
print(".".join(name))  # Connect with a period
print(" ".join(name))  # Connect with spaces
//Print results
['Albert', 'Ainstain']
AlbertAinstain
Albert.Ainstain
Albert Ainstain

Segmentation and reassembly

s = "I am, writing\npython\tbook on line"
print(s)  # Output original style
print(s.split())  # Default all space splitting
print(" ".join(s.split()))  # Reconnect, but regrettably, there are commas behind am. How to get rid of it?

//Print results
I am, writing
python	book on line
['I', 'am,', 'writing', 'python', 'book', 'on', 'line']
I am, writing python book on line

List description of another network

Python has six built-in types of sequences, but the most common are lists and tuples.

The operations that a sequence can perform include indexing, slicing, adding, multiplying, and checking members.
Lists are the most commonly used Python data type, which can appear as comma-separated values in square brackets.
Create a list by enclosing comma-separated data items in square brackets. As follows:

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Like the index of a string, the list index starts at 0. Lists can be intercepted, combined, and so on.

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
 
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

The output of the above example is as follows:

list1[0]: Google
list2[1:5]: [2, 3, 4, 5]

Update List

list = ['Google', 'Runoob', 1997, 2000]
print ("The third element is : ", list[2])
list[2] = 2001
print ("The third element updated is : ", list[2])

The output of the above example is as follows:

The third element is: 1997
The third element updated is: 2001

Delete list elements
You can use the del statement to delete elements of the list, as shown in the following example:

list = ['Google', 'Runoob', 1997, 2000]
 
print ("Original list : ", list)
del list[2]
print ("Delete the third element : ", list)

The output of the above example is as follows:

Original list: ['Google','Runoob', 1997, 2000]
Delete the third element: ['Google','Runoob', 2000]

Python list script operator
The list pair + and * operators are similar to strings. + Number is used for combination lists and * is used for repetition lists.

len([1, 2, 3]) 3 length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] combination

[`Hi!'] * 4 [`Hi!', `Hi!', `Hi!', `Hi!', `Hi!'] Repeat

Does the 3 in [1, 2, 3] True element exist in the list

for x in [1, 2, 3]: print(x, end=") 123 iteration

Python List Interception and Stitching

L = ['Google', 'Runoob', 'Taobao']
print(L[2])  # Read the third element
print(L[-2])  # Read the penultimate element from the right: count from the right
print(L[1:])  # Output all elements starting from the second element
//Print results
Taobao
Runoob
['Runoob', 'Taobao']

The list also supports splicing operations:

squares = [1, 4, 9, 16, 25]
squares += [36, 49, 64, 81, 100]  # squares = squares + [36, 49, 64, 81, 100]
print(squares)

Nested list

a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x)
print(x[0])
print(x[0][1])
//Print results
[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b

Python List Function & Method

1 len(list)

Number of list elements

2 max(list)

Returns the maximum of list elements

3 min(list)

Returns the minimum of list elements

4 list(seq)

Converting tuples to lists

Python includes the following methods:

1 list.append(obj)

Add new objects at the end of the list

2 list.count(obj)

Statistics of the number of times an element appears in a list

3 list.extend(seq)

Append multiple values in another sequence at the end of the list at once (expand the original list with a new list)

4 list.index(obj)

Find the index location of the first match of a value from the list

5 list.insert(index, obj)

Insert objects into the list

6 list.pop([index=-1])

Remove an element from the list (default last element) and return the value of that element

7 list.remove(obj)

Remove the first match of a value in the list

8 list.reverse()

Elements in the reverse list

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

Sort the original list

10 list.clear()

clear list

11 list.copy()

Duplicate List

Explanation of the third list of websites

More on the list

list.append(x)

Adding an element to the end of the list is equivalent to a [len (a):]= [x].

list.extend(L)

Adding all elements in a given list to another list is equivalent to a[len(a):] = L.

list.insert(i, x)

Insert an element at the specified location. The first parameter is the index of the element to be inserted in front of it. For example, a.insert(0, x) is inserted before the entire list, while a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)

Delete the first element in the list whose value is x. If there is no such element, an error will be returned.

list.pop([i])

Delete the element from the specified location of the list and return it. If no index is specified, a.pop() returns the last element. Elements are then deleted from the list (the square brackets on both sides of i in the method indicate that this parameter is optional, rather than requiring you to enter a pair of square brackets, which you will often encounter in the Python Library Reference Manual).

list.clear()

Delete all elements from the list. It is equivalent to del a [:].

list.index(x)

Returns the index of the first element in the list whose value is x. If there are no matching elements, an error will be returned.

list.count(x)

Returns the number of times x appears in the list.

list.sort()

Sort the elements in the list in place.

list.reverse()

The elements in the table are arranged in reverse order.

list.copy()

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

Use lists as stacks - ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The list method makes it easy to use the list as a stack, which acts as a specific data structure, and the last element of the most advanced entry is released (last in first out). Appnd () can be used to add an element to the top of the stack. An element can be released from the top of the stack using the pop() method with no specified index. For example:

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

Use lists as queues
You can also use lists as queues, queues as specific data structures, and first-in elements are released first (first-in first-out). However, lists are inefficient. Relatively fast to add and pop up from the end of the list; slow to insert and pop up at the head (because, for one element, all elements in the entire list need to be moved)
To achieve the queue, use collections.deque, which is designed for quick insertion and deletion at both ends. For example:

from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Append
queue.append("Graham")          # Append
queue.popleft()                 # delete
queue.popleft()                 # delete
print(queue)                    # Printing
//Print results
deque(['Michael', 'Terry', 'Graham'])

List Derivation Formula
List derivation provides a simple way to create lists from sequences. Ordinary applications create lists by applying operations to each member of a sequence and creating lists by returning elements, or subsequences by elements that satisfy specific conditions.

For example, suppose we create a square list, as follows:

squares = []
for x in range(10):
    squares.append(x**2)
print(squares)
//Print results
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Equivalent to:

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

Two

print([(x, y) for x in [1,2,3] for y in [3,1,4] if x != y])
//Print results
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Equivalent to:

combs = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            combs.append((x, y))
print(combs)
//Print results
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Nested list derivation

The first expression in list parsing can be any expression, including list parsing.

Consider the following 3x4 matrix consisting of three 4-length lists. Now, if you want to swap rows and columns, you can use nested list derivatives:

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

Equivalent 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])
print(transposed)

In practice, you should prefer to use built-in functions to compose complex process statements. In this case, the zip() function will do better:

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

Topics: Python github Java Google