『Python』 python基本チュートリアル(1)-基本的なデータ構造


序文

Pythonで一般的に使用されるいくつかのデータ構造を説明して整理する

1つ、リスト

1.1基本操作

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.sort( )
sorted(list)
list.reverse( )		# 倒序

1.3トラバースビュー

# 方式一
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コレクションへのリスト(重複排除)

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

1.5辞書への2つのリスト

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

1.6ネストされたリストを辞書に変換する

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

1.7リスト、タプルから文字列

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

1.8リストAとBの同じ要素と異なる要素

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

1.9リスト式

リスト式を使用すると、リストを生成するためにforループを使用する必要はありません。

[ expression for item in list if conditional ]

式は、リストを直接生成したり、式を使用したり、数学演算を実行したり、外部関数を呼び出したりすることができます。最後に、リストを生成するときにフィルタリングするif条件を使用することもできます。

2、タプル

タプルはリストに非常に似ていますが、タプルを変更することはできません(強い制約)

2.1基本操作

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トラバースビュー(リストと同じ)

# 方式一
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))

三、辞書の口述

3.1基本操作

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トラバースビュー

# 方式一
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辞書をリストに保存する

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

3.4辞書を文字列に変換する

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

3.5辞書のキーと値の変換

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

3.6辞書の理解

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

3.7辞書のマージ

重複するキーがある場合、最初の辞書のこのキーに対応する値が上書きされます。

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

4、セット

コレクション要素は繰り返されません

4.1基本操作

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トラバースビュー

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

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

5、文字列文字列

5.1基本操作

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分割文字列

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

5.3文字列の反転

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

5.4スペースを削除する

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文字列のリストを文字列に変換する

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

6、配列

6.1基本操作

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多次元配列

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

セブン、マトリックス

7.1基本操作

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

7.2ネストされたリストを行列に変換する

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

7.3配列を行列に変換する

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)) # 对角矩阵

おすすめ

転載: blog.csdn.net/libo1004/article/details/111029308