Python语法

列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def get_factors2(number):
import math
factors = []
sqrt = math.sqrt(number)
# print(f"{number}的开方数{sqrt:.3f}")
for i in range(1, int(sqrt)+1):
if number % i == 0:
factors.append(i)
if number // i != i:
factors.append(number // i)
# print(factors)
return sorted(factors)

if __name__ == '__main__':
i = 0
factors = get_factors2(100)
print(factors)
for f in factors:
print(f"factors[{i}]: {factors[i]}")
i += 1

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/env python3
import os
book_list = [
{'name':"数学1年级上册", 'url':"https://v3.ykt.cbern.com.cn/65/document/40a22857f0234ab1b1827998d588d927/pdf.pdf"},
{'name':"数学1年级下册", 'url':"https://v3.ykt.cbern.com.cn/65/document/39c42025a2d848bf8c57ff612439ceb3/pdf.pdf"},
{'name':"数学2年级上册", 'url':"https://v2.ykt.cbern.com.cn/65/document/6490bb97b5ad41fb83e2b3dbd28b8fe0/pdf.pdf"},
{'name':"数学2年级下册", 'url':"https://v2.ykt.cbern.com.cn/65/document/2a3ceb3318714414ad0d658af901ea77/pdf.pdf"},
{'name':"数学3年级上册", 'url':"https://v2.ykt.cbern.com.cn/65/document/32c6b18bca334b439ba061ac958d9d3f/pdf.pdf"},
{'name':"数学3年级下册", 'url':"https://v3.ykt.cbern.com.cn/65/document/01c4d03170af48d1b88ea5efdfcb5011/pdf.pdf"},
{'name':"数学4年级上册", 'url':"https://v1.ykt.cbern.com.cn/65/document/f86d42fd514c4945b27a4166e3deb8a3/pdf.pdf"},
{'name':"数学4年级下册", 'url':"https://v1.ykt.cbern.com.cn/65/document/d0a86fb3780b4a1f92db6025aa5683bd/pdf.pdf"},
{'name':"数学5年级上册", 'url':"https://v1.ykt.cbern.com.cn/65/document/c07eb72ef5044b339bde311968ad3e31/pdf.pdf"},
{'name':"数学5年级下册", 'url':"https://v1.ykt.cbern.com.cn/65/document/00149c6d79044fa08e7d03f78cdb4145/pdf.pdf"},
{'name':"数学6年级上册", 'url':"https://v1.ykt.cbern.com.cn/65/document/b1950c9c9dcc43919f60824c1b258b06/pdf.pdf"},
{'name':"数学6年级下册", 'url':"https://v2.ykt.cbern.com.cn/65/document/9547d96598ec4966876698c225bcfd11/pdf.pdf"}
]

for book in book_list:
# print(book['name'], book['url'])
command = f"wget {book['url']} -O {book['name']}.pdf"
print(command)
os.system(command)

字符串

f””

1
2
3
4
h = "hello"
w = "world"
f"{h} {w}"
输出:hello world

format函数

1
2
3
4
5
6
7
8
9
10
# 不带位置转换
"{} {}".format("hello", "world")
输出:hello world

# 带位置转换
"{0} {1}".format("hello", "world")
输出:hello world

"{1} {0} {1}".format("hello", "world")
输出:world hello world

字典

遍历

1
2
3
4
# 使用items()方法遍历字典
my_dict = {'name': 'Tom', 'age': 18, 'sex': '男'}
for key, value in my_dict.items():
print(key, value)
1
2
3
my_dict = {'name': 'Tom', 'age': 18, 'sex': '男'}
for key in my_dict:
print(key, ':', my_dict[key])

lambda匿名函数

1
2
3
f = lambda x: x*x
print(f(5))
print((lambda y: y*y)(10))

DataFrame

创建DataFrame对象

1
2
3
4
5
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((3, 5)))
df.columns = ['a', 'b', 'c', 'd', 'e']
print(df)

运行结果:

1
2
3
4
          a         b         c         d         e
0 0.493908 0.129874 0.715260 0.725369 0.994077
1 0.021717 0.369733 0.070762 0.940723 0.637749
2 0.201970 0.075588 0.103985 0.706798 0.635883

访问DF对象的列

1
2
print(df.columns)
print(df.columns.tolist())

运行结果:

1
2
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
['a', 'b', 'c', 'd', 'e']

访问DF对象的索引

1
print(df.index)

运行结果:

1
RangeIndex(start=0, stop=3, step=1)

删除行

1
2
df = df.drop(index=[0, 1, 2]) # 删除第0-2行
print(df)

运行结果:

1
2
3
Empty DataFrame
Columns: [a, b, c, d, e]
Index: []

创建空对象

1
2
df2 = pd.DataFrame(data=None, columns=['Name', 'Birthday', 'Address'])
print("df2:", df2)

运行结果:

1
2
3
df2: Empty DataFrame
Columns: [Name, Birthday, Address]
Index: []

打印完整数据

1
2
3
4
5
6
7
8
9
# display.max_rows的默认值是10
# display.max_columns的默认值是10
klines = self.api.get_kline_serial(self.symbols, 60, data_length=5)
with pd.option_context('display.max_rows', None,
'display.max_columns', None,
'display.width', None,
'display.max_colwidth', None
):
print(klines)

方式二、

1
2
3
4
5
6
7
8
# Permanently changes the pandas settings
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)

klines = self.api.get_kline_serial(self.symbols, 60, data_length=5)
print(klines)

运行结果:

1
2
3
4
5
6
       datetime       id    open    high     low   close  volume  open_oi  close_oi     symbol  duration
0 1.687141e+18 62033.0 2182.5 2183.0 2181.5 2182.5 51.0 47595.0 47585.0 DCE.j2309 60
1 1.687141e+18 62034.0 2182.5 2182.5 2180.0 2181.0 67.0 47585.0 47614.0 DCE.j2309 60
2 1.687141e+18 62035.0 2181.0 2181.0 2178.0 2178.0 165.0 47614.0 47622.0 DCE.j2309 60
3 1.687141e+18 62036.0 2178.0 2180.0 2177.5 2180.0 104.0 47622.0 47580.0 DCE.j2309 60
4 1.687141e+18 62037.0 2180.0 2182.0 2180.0 2182.0 80.0 47580.0 47581.0 DCE.j2309 60