Alibaba Cloud Python Training Camp (day4)


Introduction

Today I learned the two sections of conditional statements and loop statements. Python uses a lot. I didn’t know much about it before. This is something you must master. I will briefly talk about the specific usage in python. (List and Meta Groups are containers, a series of objects.)


1. List

1. List definition and creation

A list is an ordered collection, has no fixed size, and can store any number of Python objects of any type. The syntax is [element 1, element 2, …, element n].

  • The key points are the brackets and commas
  • Brackets tie all elements together
  • Comma separates each element one by one

(1). Create a list:

The demo code is as follows:

x = ['one', 'two', 'three', 'four']
print(x, type(x))
# ['one', 'two', 'three', 'four'] <class 'list'>

(2). Create a list with range() and deduction:

The demo code is as follows:

x = list(range(1, 11, -2))#-2表示在循环中递减2
print(x)
x = [i ** 2 for i in range(1, 10)]
print(x)
# [10, 8, 6, 4, 2] 
# [1, 4, 9, 16, 25, 36, 49, 64, 81]

Note:
Since the elements of the list can be any object, the pointer to the object is stored in the list. Even if you save a simple [1,2,3], there are 3 pointers and 3 integer objects.


x = [a] * 4 In the operation, only 4 references to the list are created, so once a changes, the 4 a in x will also change.

The demo code is as follows:

x = [[0] * 3] * 4
print(x)
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

a = [0] * 3
x = [a] * 4
print(x)
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

x[0][0] = 1
print(x)
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] 

(3). Create a mixed list:

The demo code is as follows:

mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix)  
# [1, 'lsgo', 3.14, [1, 2, 3]] 

Tips: A
list is not like a tuple. The content of a list can be changed (mutable), so operations such as append (extend), insert (insert), and delete (remove, pop) can all be used on it.


2. Add elements to the list

  • list.append(obj) adds a new object at the end of the list. It only accepts one parameter. The parameter can be any data type. The appended element maintains the original structure type in the list.

  • list.extend(seq) append multiple values ​​in another sequence at the end of the list at once (extend the original list with the new list)

  • list.insert(index, obj) Insert obj at index position.

The demo code is as follows:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append('Thursday')
print(x) 
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday']


x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.extend(['Thursday', 'Sunday'])
print(x)  
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday']


x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.insert(2, 'Sunday')
print(x)
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']

Note:
(1). If this element is a list, then this list will be appended as a whole, pay attention to the difference between append() and extend().
(2). Strictly speaking, append is appending, adding one thing as a whole behind the list, while extend is extending, adding all the elements in a thing after the list.


3. Delete elements in the list

  • list.remove(obj) removes the first match of a value in the list
  • list.pop([index=-1]) remove an element from the list (the last element by default), and return the value of the element
  • del var1[, var2 ……] delete single or multiple objects.

The demo code is as follows:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.remove('Monday')
print(x)  # ['Tuesday', 'Wednesday', 'Thursday', 'Friday']


x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = x.pop()
print(y)  # Friday

y = x.pop(0)
print(y)  # Monday


x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]#从Monday开始的两个元素
print(x)  # ['Wednesday', 'Thursday', 'Friday']

Note:
(1) Both .remove and pop can delete elements, the former is to specify the specific element to be deleted, and the latter is to specify an index.
(2). If you want to delete an element from the list and no longer use it in any way, use the del statement; if you want to continue to use it after deleting the element, use the method pop().


4. Get the elements in the list

  • Get a single element from the list through the index value of the element. Note that the index value of the list starts from 0.
  • By specifying the index as -1, Python returns the last list element, index -2 returns the penultimate list element, and so on.

The demo code is as follows:

x = ['Monday', 'Tuesday', 'Wednesday', ['Thursday', 'Friday']]
print(x[0], type(x[0]))  # Monday <class 'str'>
print(x[-1], type(x[-1]))  # ['Thursday', 'Friday'] <class 'list'>
print(x[-2], type(x[-2]))  # Wednesday <class 'str'>

The usual way to write a slice is start : stop : step

  • Case 1 - "start:" to step1 (default) from the number startto the end of the list slices.
  • Case 2-": stop" uses step as 1 (default) to slice from the head of the list to the number stop.
  • Case 3-"start: stop" uses step as 1 (default) to slice from start to stop.
  • Case 4-"start: stop: step" slices from number start to number stop with specific steps. Note that setting step to -1 at the end is equivalent to sorting the list in reverse.
  • Case 5-":" Copy all elements in the list (shallow copy).

The demo code is as follows:

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x[3:])  # ['Thursday', 'Friday']
print(x[-3:])  # ['Wednesday', 'Thursday', 'Friday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:3])  # ['Monday', 'Tuesday', 'Wednesday']
print(week[:-3])  # ['Monday', 'Tuesday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:3])  # ['Tuesday', 'Wednesday']
print(week[-3:-1])  # ['Wednesday', 'Thursday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:4:2])  # ['Tuesday', 'Thursday']
print(week[:4:2])  # ['Monday', 'Wednesday']
print(week[1::2])  # ['Tuesday', 'Thursday']

eek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:])  
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

5. Commonly used operators for lists

  • Equal sign operator: ==
  • Concatenation operator: +
  • Repeat operator: *
  • Membership operator: in, not in

There are two ways of list splicing, using plus sign and multiplication sign, the former splicing end to end, and the latter copy splicing.

The demo code is as follows:

list1 = [123, 456]
list2 = list1 * 3
print(list2)  # [123, 456, 123, 456, 123, 456]

6. Other ways to list

  • list.count(obj) count the number of times an element appears in the list
  • list.index(x[, start[, end]]) Find the index position of the first match of a value from the list
  • list.reverse() reverse the elements in the list

The demo code is as follows:

list1 = [123, 456] * 3
num = list1.count(123)
print(num)  # 3


print(list1.index(123))  # 0
print(list1.index(123, 1))  # 2
print(list1.index(123, 3, 7))  # 4



x = [123, 456, 789]
x.reverse()
print(x)  # [789, 456, 123]

list.sort(key=None, reverse=False) Sort the original list.

  • key-It is mainly used to compare the element. There is only one parameter. The parameter of the specific function is taken from the iterable object and specifies an element in the iterable object for sorting.
  • reverse-sorting rule, reverse = True for descending order, reverse = False for ascending order (default).
  • This method has no return value, but it sorts the objects in the list.

The demo code is as follows:

x = [123, 456, 789, 213]
x.sort()
print(x)
# [123, 213, 456, 789]

x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]


Two, tuple

1. Create and access a tuple

  • Python tuples are similar to lists. The difference is that tuples cannot be modified after they are created, similar to strings.
  • Use parentheses for tuples and square brackets for lists.
  • Tuples are similar to lists, and integers are used to index and slice them.

The demo code is as follows:

t1 = (1, 10.31, 'python')
print(t1)
#(1, 10.31, 'python') 

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1])  # 2
print(tuple1[5:])  # (6, 7, 8)
print(tuple1[:5])  # (1, 2, 3, 4, 5)

Note:
You can use parentheses () to create tuples, or you can use nothing. For readability, it is recommended to use ().
When the tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators.


Create a two-dimensional tuple:

The demo code is as follows:

a=(2,'zmt',9.45),('zgk','bcj','0')
print(a)
#(2,'zmt',9.45),('zgk','bcj','0')

print(a[0],a[0][1],a[1][0])
#(2,'zmt',9.45),'zmt',zgk

print(a[0][0:2])
#(2,'zmt')

2. Modify and add a tuple

The demo code is as follows:

t = (1, 2, 3, ['d', 5, 6])
t[3][0]=4
print(t)
#(1, 2, 3, [4, 5, 6])

t=t[2:]+'zmt'+t[:2]
print(t)
#(1, 2,'zmt',3, [4, 5, 6])

Tips:
Tuples are immutable, so you cannot directly assign values ​​to the elements of the tuple, but as long as the elements in the tuple can be changed (mutable), then we can directly change its elements, pay attention to this and assignment The elements are different.


3. Operators related to tuples

  • Equal sign operator: ==
  • Concatenation operator: +
  • Repeat operator: *
  • Membership operator: in, not in

This code will not be shown to everyone, there is this before.

4. Built-in methods

The tuple size and content cannot be changed, so there are only two methods: count and index.

The demo code is as follows:

t = (1, 10.31, 'python')
print(t.count('python'))  #count('python') 是记录在元组 t 中该元素出现几次,显然是 1 次
# 1
print(t.index(10.31))  #index(10.31) 是找到该元素在元组 t 的索引,显然是 1
# 1

5. Unzip the tuple

(1). Unpack one-dimensional tuples (there are several elements on the left bracket to define several variables)

The demo code is as follows:

t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python

(2). Decompress the two-dimensional tuple (define variables according to the tuple structure in the tuple)

The demo code is as follows:

t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python

(3). If you only want a few elements in the tuple, use the wildcard *, which is called wildcard in English, which represents one or more elements in computer language. The following example is to throw multiple elements to the rest variable.

The demo code is as follows:

t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]

Guess you like

Origin blog.csdn.net/qq_44250569/article/details/108761032