python知识补足

1.class的init功能,初始化class,给出一些初始值

__init__可以理解成初始化class的变量,取自英文中initial 最初的意思.可以在运行时,给初始值附值,

1 class Calculator:
2     name='good calculator'
3     price=18
4     def __init__(self,name,price,height,width,weight):   # 注意,这里的下划线是双下划线
5         self.name=name
6         self.price=price
7         self.h=height
8         self.wi=width
9         self.we=weight

在创建一个class对象的时候 ,可以赋予初始值

2.读写文件,存储在变量中

my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.

my_file.write(text)               #该语句会写入先前定义好的 text
my_file.close()                   #关闭文件

给文件增加内容,注意文件以"a"形式打开

1 append_text='
This is appended file.'  # 为这行文字提前空行 "
"
2 my_file=open('my file.txt','a')   # 'a'=append 以增加内容的形式打开
3 my_file.write(append_text)
4 my_file.close()

读取文件内容 file.read()

按行读取 file.readline()

所有行读取 file.readlines()

3.variable=input() 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量

4.zip运算

 1 a=[1,2,3]
 2 b=[4,5,6]
 3 ab=zip(a,b)
 4 print(list(ab))
 5 for i,j in zip(a,b):
 6      print(i/2,j*2)
 7 """
 8 0.5 8
 9 1.0 10
10 1.5 12
11 """

map运算,参考菜鸟教程Python内置函数

 1 >>>def square(x) :            # 计算平方数
 2 ...     return x ** 2
 3 ... 
 4 >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
 5 [1, 4, 9, 16, 25]
 6 >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
 7 [1, 4, 9, 16, 25]
 8  
 9 # 提供了两个列表,对相同位置的列表数据进行相加
10 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
11 [3, 7, 11, 15, 19]

5.pickle 保存

 1 import pickle
 2 
 3 a_dict = {'da': 111, 2: [23,1,4], '23': {1:2,'d':'sad'}}
 4 
 5 # pickle a variable to a file
 6 file = open('pickle_example.pickle', 'wb')
 7 pickle.dump(a_dict, file)
 8 file.close()
 9 
10 #读取
11 with open('pickle_example.pickle', 'rb') as file:
12     a_dict1 =pickle.load(file)

 6.set集合以及基本操作,具体详细函数见菜鸟教程python集合

s.add( x )          #添加,还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:s.update(x),且可以添加多个,以逗号隔开

s.remove( x )    #移除

len(s)                #元素个数

s.clear()            #清空

len(s)                #判断元素是否在集合中存在

s.union(x)         #返回两个集合的并集,x可以为多个,逗号隔开

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

z = x.symmetric_difference(y)
     #返回两个集合中不重复的元素集合。

7.杂项

两个列表相加,直接用+连接即可

8.     .format字符串格式化

'my name is {} ,age {}'.format('hoho',18)
'my name is hoho ,age 18'
凤舞九天
原文地址:https://www.cnblogs.com/ywheunji/p/10101008.html