『Python』python basic tutorial (1)-basic data structure


Preface

Explain and organize some commonly used data structures in python

One, list

1.1 Basic operation

list = [1, 2, 3, 'A', 'B', 'C']
list.append('D')		  	# 添加
list.insert(1, '1.5')		# 指定位置添加
list.pop( )				    # 删除最后一个元素
list.remove('C')	     	# 删除指定值
list.pop(1)				   	# 删除指定位置
len(list)				   	# 返回列表长度

1.2 List sorting

list.sort( )
sorted(list)
list.reverse( )		# 倒序

1.3 Traverse view

# 方式一
for v in list:
    print(v)

# 方式二
for i in range(len(list)):
    print ("index = %s,value = %s" % (i, list[i]))

# 方式三
for i, v in enumerate(list):
    print ("index = %s,value = %s" % (i, v))

1.4 List to collection (de-duplication)

list1 = [6, 7, 7, 8, 8, 9]
set(list1)			# {6, 7, 8, 9}

1.5 Two lists to dictionary

list1 = ['key1', 'key2', 'key3']
list2 = ['1', '2', '3']
dict(zip(list1, list2))			# {'key1': '1', 'key2': '2', 'key3': '3'}

1.6 Convert Nested List to Dictionary

list3 = [['key1', 'value1'], ['key2', 'value'2], ['key3', 'value3']]
dict(list3)			# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

1.7 List, tuple to string

list4 = ['a', 'b', 'c']
''.join(list4)		# 'abc'
tup1 = ('a', 'b', 'c')
''.join(tup1)		# 'abc'

1.8 The same and different elements of lists A and B

set(A) & set(B)		# 相同元素
set(A) ^ set(B)		# 不同元素

1.9 List expressions

With a list expression, there is no need to use a for loop to generate a list

[ expression for item in list if conditional ]

The expression can directly generate a list, or use an expression, do some mathematical operations, or even call an external function. Finally, you can also use if conditions to filter when generating the list.

Two, tuple

Tuple is very similar to list, but tuple cannot be modified (strong constraint)

2.1 Basic operation

tuple = (1, 2, 3, 'A', 'B', 'C')
tuple = ([1, 2, 3, 'A', 'B', 'C'], 4, 'D')
list = ([1, 2, 3, 'A', 'B', 'C']) 	# 元组中只有1个列表,这种写法结果变成了列表,不是元组,也不是集合
print(tuple)				        # 查看
tuple = tuple + ('D',)		    	# 虽不能直接改,但可与其他方法添加
del tuple				           	# 删除元组

2.2 Traverse view (same as list)

# 方式一
for v in tuple:
    print(v, end=’’)

# 方式二
for i in range(len(tuple)):
   	print ("index = %s,value = %s" % (i, tuple[i]))

# 方式三    
for i, v in enumerate(tuple):
    print ("index = %s,value = %s" % (i, v))

Three, dictionary dict

3.1 Basic operation

dict = {
    
    'name':'kk', 'age':100}
print(dict['age'])					# 查看value
print(dict.keys())
dict['age'] = 18					# 修改
dict['birthday'] = '1900-01-01'		# 添加 
del dict['birthday']				# 删除键值对

3.2 Traverse view

# 方式一
for k in dict:
    print('%s = %s' % (k, dict[k]))

# 方式二
for k in dict.keys():
    print('%s = %s' % (k, dict[k]))

# 方式三
for k, v in dict.items():
    print('%s = %s' % (k, v))

3.3 Store dictionaries in the list

a = [{
    
    "name": "mm", "age": 10}, {
    
    "name": "qq", "age": 20}, {
    
    "name": "hh", "age": 50}]
# 遍历列表
for item in a:
    print(item, item['name'])

3.4 Convert dictionaries to strings

dict1 = {
    
    'a': 1, 'b': 2}
str(dict1)		# '{'a': 1, 'b': 2}'

3.5 Dictionary key and value conversion

dict2 = {
    
    'a': 1, 'b': 2, 'c': 3}
{
    
    value: key for key, value in dict2.items()}	# {1: 'a', 2: 'b', 3: 'c'}

3.6 Dictionary comprehension

d = {
    
    key: value for (key, value) in iterable}

3.7 Merging of dictionaries

If there is a duplicate key, the value corresponding to this key in the first dictionary will be overwritten.

dict1 = {
    
    'a':1, 'b':2}
dict2 = {
    
    'c':4, 'b':3}
merged = {
    
    **dict1, **dict2}
print(merged)

Four, set

Collection elements are not repeated

4.1 Basic operation

myset1 = set([1, 2, 3, 'A', 'B', 'C'])
myset2 = set([1, 2, 'B', 'C'])
print(myset1)			    # 查看
myset1.add('D')			    # 添加,{1, 2, 3, 'C', 'A', 'B', 'D'}
myset1.remove('D')		  	# 删除
myset1.pop()		        # 移除最早值(类似于队列)

myset1 | myset2			    # 并集
myset1 & myset2			  	# 交集
myset1 - myset2			   	# 差集

4.2 Traverse view

# 方式一
for v in myset:
    print(v)

# 方式二
for i, v in enumerate(myset):
    print('index = %s, value = %s' % (i, v))

Five, string string

5.1 Basic operation

s = 'aabbcc'
list(s)				# 字符串列表 ['a'', 'a', 'b', 'b', 'c', 'c']
tuple(s)			# 字符串转元组 ('a', 'a', 'b', 'b', 'c', 'c')
set(s)				# 字符串转集合 {'a', 'b', 'c'}
dict2 = eval("{'name:' ljq, 'age:': 24}")       # 字符串转字典

5.2 Split string

a = 'a b c'
a.split(' ')		# ['a', 'b', 'c']

5.3 String reversal

a = 'string'
print(a[::-1])

5.4 Remove spaces

str1 = ' abcdefg'
str2 = 'abcdefg '
str1.strip()	   # 去除 str 两端空格 (strip())
str1.lstrip()	   # 去除 str 左端空格 (lstrip())
str2.rstrip()	   # 去除 str 右端空格 (rstrip())

# str 空格替换(replace(), 推荐使用)
str0 = ' a b c d e f g '
print(str0.replace(' ', ','))

# str 重新组合替换空格(使用split分割字符后重新组合,效率低)
str = ' a b c d e f g '
print(','.join(str.split(' ')))

# 正则表达式去除空格(用 sub() 方法替换)
import re
str = ' a b c d e f g '
print(re.sub(' ', ',', str))

5.5 Turn a list of strings into a string

mylist = ['The', 'quick', 'brown', 'fox']
mystring = " ".join(mylist)

Six, array

6.1 Basic operation

from numpy import *
arr1 = array([2, 2, 2])			# 数组
arr2 = array([2, 3, 5])
arr3 = arr1 + arr2				# 数组相加
arr4 = arr1 * arr2				# 数组相乘
print(arr3)
print(arr4)

6.2 Multidimensional array

arr5 = array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(arr5)				# 查看多维数组
print(arr5[1, 0])		# 查看多维数组的指定元素
print(arr5[1][0])		# 查看多维数组的指定元素

Seven, matrix

7.1 Basic operation

import numpy as np
mat0 = np.mat([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(mat0)

7.2 Convert nested list to matrix

list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],]
mat1 = np.mat(list)		# np.matrix 函数名发生变化
print(mat1)

7.3 Convert Array to Matrix

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
mat2 = np.mat(arr)
print(mat2)
mat = np.mat(np.ones(3, 4))  # 3 行 4列值为 1 的矩阵
mat = np.mat(eye(4, 4, dtype=int)) # 对角矩阵

Guess you like

Origin blog.csdn.net/libo1004/article/details/111029308
Recommended