python--python basics--sequence introduction

table of Contents

One: Sequence

1.1 Index

1.2 Slicing

1.3 Sequence addition

1.4 Sequence multiplication

1.5 Check whether an element is a member of a sequence

1.6 Calculate the length, maximum and minimum of the sequence

1.7 Other built-in functions of sequence

Second list

2.1 Creation and deletion of lists

2.2 Access list

2.3 Traverse the list

2.4 Add, modify, delete list elements

2.5 Statistics and calculations on the list

2.6 Sort the list

2.7 List comprehensions

2.8 Two-dimensional list

Triad

3.1 Creation and deletion of tuples 

3.2 Accessing tuple elements

3.3 Modify tuple elements

3.4 Tuple comprehension

Four. Dictionary

4.1 Dictionary creation and deletion

4.2 Accessing the dictionary through key-value pairs

4.3 Iterating over the dictionary

4.4 Add, modify and delete dictionary elements

4.5 Dictionary comprehension

Five. Collection

5.1 Collection creation

5.2 Adding and deleting collections

5.3 Set operations


One: Sequence

In python, sequence is the most basic data structure, it is a continuous memory space used to store multiple values.

There are 5 commonly used sequence structures built into python, namely lists, tuples, sets, dictionaries and strings.

Next, we will introduce the common operations of the sequence.

1.1 Index

Every element in python has a number, which also becomes an index. This index is incremented from 0.

[Note]: Python's index is special, its index can be negative, and the index of negative number is counted from right to left.

That is to count from the last element, that is, the index value of the last element is -1.

verse = ["春天","夏天","秋天","冬天"]
print(verse[2]) #秋天
print(verse[-1]) #冬天

1.2 Slicing

Slicing is another way to access elements in a sequence, it can access elements within a certain range. A new sequence can be generated through the slicing operation.

The slicing operation syntax:

sname[start : end : step] #Use a colon, not a comma, the interval is left closed and right open

verse = ["春天","夏天","秋天","冬天"]
print(verse[1:3:1])  #['夏天', '秋天']

1.3 Sequence addition

In python, two types of sequence addition operations are supported, that is, to connect two sequences without removing duplicate elements, using the (+) operator to achieve

verse = ["春天","夏天","秋天","冬天"]
verse2 = ["昨天","今天","明天"]
print(verse+verse2)
#['春天', '夏天', '秋天', '冬天', '昨天', '今天', '明天']

[Explanation]: When adding sequences, the same type of sequence means that the same is a list, tuple, set, etc., and the types of elements in the sequence can be different .

1.4 Sequence multiplication

In python, multiplying a sequence by the number n will generate a new sequence. The content of the new sequence is the result of the original sequence being repeated n times.

phone = ["apple","华为","小米"]
print(phone*3)
#['apple', '华为', '小米', 'apple', '华为', '小米', 'apple', '华为', '小米']

1.5 Check whether an element is a member of a sequence

The in keyword checks whether an element is a member of the sequence

The not in keyword implements to check whether an element is not included in the specified sequence

1.6 Calculate the length, maximum and minimum of the sequence

len() function: returns how many elements the sequence contains

max() function: returns the largest element in the sequence

min() function: returns the smallest element in the sequence

num = [12,14,66,9,245,1,90]
print(len(num))  #7
print(max(num))  #245
print(min(num))  #1

1.7 Other built-in functions of sequence

list(): convert a sequence to a list

str(): Convert sequence to string

sum(): Calculate the sum of elements

sorted(): sort the elements

reversed(): Reverse the elements in the sequence

enumerate(): Combine the sequence into an index sequence, which is mostly used in a for loop

Second list

2.1 Creation and deletion of lists

1) Use the assignment operator to create the list directly

list1 = ["我是最棒的","我是做大事的人","我一定会成功"]

2) Create an empty list

emptylist = []

3) Create a list of values

Use the list() function

list2 = list(["hello","world"])
#注意中括号不能省掉

You can also use the list() function to directly convert the looped result of the range() function into a list

list(range(10,20,2))

4) Delete the list

del listname

2.2 Access list

list1 = ["我是最棒的","我是做大事的人","我一定会成功"]
print(list1[2])  #我一定会成功

You can also use the index() mentioned earlier

2.3 Traverse the list

1) Directly use for loop to achieve

for item in listname:
    print(item)

2) Use for loop and enumerate() function to output index value and element content at the same time

list1 = ["我是最棒的","我是做大事的人","我一定会成功"]
for index, item in enumerate(list1):
    print(index,item)  #我一定会成功
#0 我是最棒的
#1 我是做大事的人
#2 我一定会成功

Supplement: The print() function in python wraps output by default. In order not to wrap the output, we can use "end = '' "in print()

2.4 Add, modify, delete list elements

1) Add elements

In addition to using the plus sign "+" to connect the two sequences, we recommend using the append() method .

phone = ["oppo","三星","小米","华为"]
phone.append("apple")
print(len(phone))
print(phone)

In addition, you can also use the insert() method to insert elements into the specified position of the list, but this method is not efficient.

Supplement: If you want to add all the elements in one list to another list, you can use the extend() method of the list object.

phone1 = ["oppo","三星","小米","华为"]
phone2 = ["诺基亚","魅族"]
phone1.extend(phone2)
print(phone1)
#['oppo', '三星', '小米', '华为', '诺基亚', '魅族']

2) Modify elements

To modify an element, you only need to get the element through the index, and then re-assign it.

phone1 = ["oppo","三星","小米","华为"]
phone1[2]= "红米"
print(phone1)
# ['oppo', '三星', '红米', '华为']

3) Delete elements

  • Delete according to index
del phone[1]
  • Delete based on element value
phone.remove("华为")

2.5 Statistics and calculations on the list

1) Get the number of occurrences of the specified element

phone1 = ["oppo","三星","小米","华为","oppo"]
print(phone1.count("oppo"))  #2

2) Get the index of the first occurrence of the specified element

phone1 = ["oppo","三星","小米","华为","oppo"]
print(phone1.index("oppo"))  #

3) The sum of the elements of the list of statistical values

grade = [222,44,66,88,9,2]
print(sum(grade)) #431

2.6 Sort the list

1) Use the sort() method: The original list will change

grade = [222,44,66,88,9,2]
print(grade.sort()) #None
print(grade) #[2, 9, 44, 66, 88, 222]

The default is ascending order, if you want to sort in descending order, you need to use reverse = True

grade = [222,44,66,88,9,2]
grade.sort(reverse=True)
print(grade) #[222, 88, 66, 44, 9, 2]

2) Use the built-in sorted() function to achieve

Note that after the sorted() method is sorted, the order of the elements of the original list remains unchanged, because a copy of the original list will be created.

grade = [222,44,66,88,9,2]
new_grade= sorted(grade)
print(grade) #[222, 44, 66, 88, 9, 2]
print(new_grade) #[2, 9, 44, 66, 88, 222]

2.7 List comprehensions

Use list comprehensions to quickly generate a list

list = [expression for var in range]
import random
randomnumber = [random.randint(10,100) for i in range(10)]
print(randomnumber)
#[84, 20, 73, 31, 31, 76, 30, 80, 45, 53]

2.8 Two-dimensional list

1) Directly define a two-dimensional list

list1 = [['a','b','c'],['d','e','f'],['q','w','e'],['a','s','d']]
print(list1)
# [['a', 'b', 'c'], ['d', 'e', 'f'], ['q', 'w', 'e'], ['a', 's', 'd']]

2) Use nested for loop creation

arr = []
for i in range(4):
    arr.append([])
    for j in range(5):
        arr[i].append(j)
print(arr)
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

3) Use list comprehension to create

arr = [[j for j in range(5)] for i in range(4)]
print(arr)
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Triad

3.1 Creation and deletion of tuples 

1) Use the assignment operator to directly create a tuple

num1 = (12,34,67,11,3,99)
print(num1)
print(type(num1))
#(12, 34, 67, 11, 3, 99)
#<class 'tuple'>

2) Create empty tuple

emptytuple = ()

3) Create numeric elements

print(tuple(range(10,20,2)))
#(10, 12, 14, 16, 18)

4) Delete elements

del tuplename

3.2 Accessing tuple elements

team = ("火箭","骑士","快船","湖人")
print(team[1])
for index, item in enumerate(team):
    print(index,item)
#骑士
#0 火箭
#1 骑士
#2 快船
#3 湖人

3.3 Modify tuple elements

A tuple is an immutable sequence, so we cannot modify its single element value,

But the tuple is not completely unmodifiable, we can reassign the tuple

coffeename = ("拿铁","卡布奇诺","曼特宁")
coffeename = ("拿铁2","卡布奇诺3")
print(coffeename) #('拿铁2', '卡布奇诺3')

3.4 Tuple comprehension

#To convert to a tuple, use the tuple() function

import random
randomnumber = (random.randint(10,100) for i in range(10))
randomnumber = tuple(randomnumber)
print(randomnumber)
# (69, 30, 31, 50, 22, 86, 50, 32, 29, 85)

Four. Dictionary

Similar to a list, a dictionary is also a variable sequence, but unlike a list, it is an unordered variable sequence.

The saved content is stored in the form of key-value pairs.

The key is unique and there are multiple values

The same key is not allowed to appear twice, if it appears twice, the latter value will be remembered .

4.1 Dictionary creation and deletion

1) To create a dictionary, a colon is used to separate the key and value, and two adjacent elements are separated by a comma, and all elements are placed in a pair of "{ }".

dictionary = {"qq":"282439859","bolg":"yezonghui"}
print(dictionary)
print(type(dictionary))
#{'qq': '282439859', 'bolg': 'yezonghui'}
#<class 'dict'>

2) Create a dictionary through the mapping function

di = dict(zip(list1,list2))

Supplement: zip() function: used to combine elements at corresponding positions of multiple lists or tuples into tuples, and return a zip object containing these contents

name = ["q","w","e","r"]
sign = ["1","2","3","5"]
dirctionary2 = dict(zip(name,sign))
print(dirctionary2)
# {'q': '1', 'w': '2', 'e': '3', 'r': '5'}

4.2 Accessing the dictionary through key-value pairs

Use [] or get() method

d1 = {"春天":"学语文","夏天":"学数学","秋天":"学英语","冬天":"学历史"}
print(d1["夏天"])  #学数学
print(d1.get("秋天"))  #学英语

4.3 Iterating over the dictionary

Get the dictionary view:

 keys(): Get all keys in the dictionary

values(): Get all values ​​in the dictionary

items(): Get all key and value pairs in the dictionary

d1 = {"春天":"学语文","夏天":"学数学","秋天":"学英语","冬天":"学历史"}
for item in d1.items():
    print(item)
#('春天', '学语文')
#('夏天', '学数学')
#('秋天', '学英语')
#('冬天', '学历史')
d1 = {"春天":"学语文","夏天":"学数学","秋天":"学英语","冬天":"学历史"}
for key,value in d1.items():
    print(key,value)
#春天 学语文
#夏天 学数学
#秋天 学英语
#冬天 学历史

4.4 Add, modify and delete dictionary elements

Add directly

d1 = {"春天":"学语文","夏天":"学数学","秋天":"学英语","冬天":"学历史"}
d1["今天"] = "学习"
print(d1)
#{'春天': '学语文', '夏天': '学数学', '秋天': '学英语', '冬天': '学历史', '今天': '学习

delete

del d1["春天"]

4.5 Dictionary comprehension

import random
ranomdict = {i:random.randint(10,100) for i in range(1,5)}
print(ranomdict)
#{1: 77, 2: 77, 3: 100, 4: 79}

Five. Collection

5.1 Collection creation

1) Create directly using {}

set1 = {1,4,6,7}

2) Created using the set() function

set1 = set(1,2,3,4,8)

[Note]: When creating an empty dictionary, you can only use set(), because a pair of {} means creating an empty dictionary

5.2 Adding and deleting collections

1) Add elements to the collection using the add() method

2) Remove elements from the collection using remove()

5.3 Set operations

1) Are the two sets equal == or! =

2) Is it a subset issubset()

3) Whether it is a superset: issuperset()

4) Intersection: & or intersection()

5) Union: | or union()

6) Difference:-or difference()

[Note]: The learning of strings in the sequence will be summarized in the next blog

Guess you like

Origin blog.csdn.net/yezonghui/article/details/113244669