new1
This commit is contained in:
parent
cd1241e256
commit
bf2717ff91
|
@ -0,0 +1,13 @@
|
|||
class Cat:
|
||||
name = ''
|
||||
def __init__(self):
|
||||
# self.name = 'Tom'
|
||||
print('init')
|
||||
def __str__(self):
|
||||
return(self.name)
|
||||
def drink(self):
|
||||
print('drink')
|
||||
cat = Cat()
|
||||
cat.name = 'Tom'
|
||||
print(f'我是小猫{cat},我的id是{id(cat)}',cat,cat.name)
|
||||
cat.drink()
|
|
@ -0,0 +1,12 @@
|
|||
# 在开发中,如果希望在 创建对象的同时,就设置对象的属性,可以对 __init__ 方法进行 改造
|
||||
class Cat:
|
||||
def __init__(self,name):
|
||||
self.name = 'Tom'
|
||||
print('init')
|
||||
def __str__(self):
|
||||
return(self.name)
|
||||
def drink(self):
|
||||
print('drink')
|
||||
cat = Cat('Tom')
|
||||
print(f'我是小猫{cat},我的id是{id(cat)}',cat,cat.name)
|
||||
cat.drink()
|
|
@ -0,0 +1,19 @@
|
|||
def car(type,price):
|
||||
print(f'car的价格是 {price}, 类型是{type}')
|
||||
car(12,'qqq')
|
||||
|
||||
class Car:
|
||||
def __init__(self,type,price):
|
||||
self.type = type
|
||||
self.price = price
|
||||
self.distance = 0
|
||||
def carinfo(self):
|
||||
print(f'car的价格是 {self.price}, 类型是{self.type},行驶了{self.distance}')
|
||||
def drive(self,distance):
|
||||
self.distance +=distance
|
||||
self.price -= 10*distance
|
||||
car1 = Car('aa',2000)
|
||||
car1.carinfo()
|
||||
car1.drive(20)
|
||||
car1.carinfo()
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
class Person:
|
||||
def __init__(self,name,age):
|
||||
self.name = name
|
||||
self.__age = age
|
||||
def getAge(self):
|
||||
return self.__age
|
||||
def setAge(self,age):
|
||||
self.__age = age
|
||||
p = Person('aa',23)
|
||||
print(p.name,p.getAge())
|
|
@ -0,0 +1,30 @@
|
|||
class Teacher:
|
||||
def __init__(self, name, age,speak):
|
||||
self.name = name
|
||||
self.__age = age
|
||||
self.__speak = speak
|
||||
|
||||
@property #注意1.@proterty下面默认跟的是get方法,如果设置成set会报错。
|
||||
def age(self):
|
||||
return self.__age
|
||||
|
||||
@age.setter #注意2.这里是使用的上面函数名.setter,不是property.setter.
|
||||
def age(self,age):
|
||||
if age > 150 and age <=0: #还可以在setter方法里增加判断条件
|
||||
print("年龄输入有误")
|
||||
else:
|
||||
self.__age = age
|
||||
|
||||
@property
|
||||
def for_speak(self): #注意2.这个同名函数名可以自定义名称,一般都是默认使用属性名。
|
||||
return self.__speak
|
||||
|
||||
@for_speak.setter
|
||||
def for_speak(self, speak):
|
||||
self.__speak = speak
|
||||
|
||||
t1 = Teacher("herry",45,"Chinese")
|
||||
t1.age = 38 #注意4.有了property后,直接使用t1.age,而不是t1.age()方法了。
|
||||
t1.for_speak = "English"
|
||||
|
||||
print(t1.name,t1.age,t1.for_speak) #herry 38 English
|
|
@ -0,0 +1,27 @@
|
|||
import math
|
||||
class Shape:
|
||||
def __init__(self,color):
|
||||
self.color = color
|
||||
def area(self):
|
||||
return 0
|
||||
def __str__(self):
|
||||
return f'color is {self.color}'
|
||||
|
||||
class Circle(Shape):
|
||||
def __init__(self,color,r):
|
||||
super().__init__(color)
|
||||
self.r = r
|
||||
def area(self):
|
||||
return self.r**2*math.pi
|
||||
class Retangle(Shape):
|
||||
def __init__(self,color,a,b):
|
||||
# super().__init__(color)
|
||||
self.color = color
|
||||
self.a = a
|
||||
self.b = b
|
||||
def area(self):
|
||||
return self.a*self.b/2
|
||||
s = Shape('red')
|
||||
c1 = Circle('green',13)
|
||||
r = Retangle('green',13,22)
|
||||
print(r.area())
|
|
@ -0,0 +1,21 @@
|
|||
# 也就是说,先创建一个实例对象,之后不管创建多少个,返回的永远都是第一个实例对象的内存地址。可以这样实现:
|
||||
|
||||
# 重写new方法很固定,返回值必须是这个
|
||||
# 这样就避免了创建多份。
|
||||
# 创建第一个实例的时候,_instance是None,那么会分配空间创建实例。
|
||||
# 此时的类属性已经被修改,_instance不再为None
|
||||
# 那么当之后实例属性被创建的时候,由于_instance不为None。
|
||||
# 则返回第一个实例对象的引用,即内存地址。
|
||||
# 这样就应用了单例模式。
|
||||
class A():
|
||||
_instance = None
|
||||
def __new__(cls,*args,**kwargs):
|
||||
if A._instance == None:
|
||||
A._instance = super().__new__(cls)
|
||||
return A._instance
|
||||
|
||||
|
||||
a1 = A()
|
||||
print(id(a1))
|
||||
a2 = A()
|
||||
print(id(a2))
|
|
@ -0,0 +1,37 @@
|
|||
# 实例1—— 学生注册
|
||||
|
||||
# 定义变量---学生学号
|
||||
studentNo = 232535
|
||||
|
||||
# 定义变量---学生密码
|
||||
stuentPassword = "123"
|
||||
|
||||
# 在程序中,如果要输出变量的内容,需要使用 print 函数
|
||||
print(studentNo)
|
||||
print(stuentPassword)
|
||||
|
||||
# 定义柿子价格变量
|
||||
price = 8.5
|
||||
|
||||
# 定义购买重量
|
||||
weight = 7.5
|
||||
|
||||
# 计算金额
|
||||
money = price * weight
|
||||
|
||||
print(money)
|
||||
|
||||
first_name = "三"
|
||||
last_name = "张"
|
||||
print(first_name + last_name)
|
||||
print("-" * 50)
|
||||
|
||||
# 变量的格式化输出
|
||||
print("我的名字叫 %s,请多多关照!" % stuentPassword)
|
||||
print("我的学号是 %06d" % studentNo)
|
||||
print("苹果单价 %.02f 元/斤,购买 %.02f 斤,需要支付 %.02f 元" % (price, weight, money))
|
||||
print("数据比例是 %.02f%%" % (money * 100))
|
||||
|
||||
# 使用format
|
||||
str = "{}曰:学而时习之,不亦说乎。".format("孔子")
|
||||
print(str)
|
|
@ -0,0 +1,60 @@
|
|||
java = 86
|
||||
python = 68
|
||||
|
||||
if (80 <= java < 90) or (80 <= python < 90):
|
||||
print('良好')
|
||||
# 练习1
|
||||
# 我想买车,买什么车决定于我在银行有多少存款
|
||||
# 如果我的存款超过500万,我就买路虎
|
||||
# 否则,如果我的存款超过100万,我就买宝马
|
||||
# 否则, 如果我的存款超过50万,我就买迈腾
|
||||
# 否则, 如果我的存款超过10万,我就买福特
|
||||
# 否则, 如果我的存款10万以下 ,我买比亚迪
|
||||
# 练习2
|
||||
# 输入小明的考试成绩,显示所获奖励
|
||||
# 成绩==100分,爸爸给他买辆车
|
||||
# 成绩>=90分,妈妈给他买MP4
|
||||
# 90分>成绩>=60分,妈妈给他买本参考书
|
||||
# 成绩<60分,什么都不买
|
||||
|
||||
for letter in 'www.baidu.com':
|
||||
print(letter)
|
||||
for value in range(1,100):
|
||||
print(value)
|
||||
# 练习3
|
||||
# 打印质数
|
||||
|
||||
for num in range(2,100):
|
||||
for i in range(2,num):
|
||||
if num%i == 0:
|
||||
break;
|
||||
else:
|
||||
print("%d is zhishu " % num)
|
||||
|
||||
# 练习4
|
||||
# 打印九九乘法表
|
||||
for i in range(1,10):
|
||||
for j in range(1,i+1):
|
||||
print("{}*{} = {} \t".format(i,j,i*j),end=" ")
|
||||
print()
|
||||
|
||||
# 随机数的处理
|
||||
综合练习---猜数字
|
||||
|
||||
# 计算机要求用户输入数值范围的最小值和最大值。计算机随后“思考”出在这个范围之内的一个随机数,并且重复地要求用户猜测这个数,直到用户猜对了。在用户每次进行猜测之后,计算机都会给出一个提示,并且会在这个过程的最后显示出总的猜测次数。这个程序包含了几种类型的我们学过的 Python 语句,例如,输入语句、输出语句、赋值语句、循环和条件语句
|
||||
import random
|
||||
|
||||
smaller = int(input("Enter the smaller number: "))
|
||||
larger = int(input("Enter the larger number: "))
|
||||
myNumber = random.randint(smaller, larger)
|
||||
count = 0
|
||||
while True:
|
||||
count += 1
|
||||
userNumber = int(input("Enter your guess: "))
|
||||
if userNumber < myNumber:
|
||||
print("Too small")
|
||||
elif userNumber > myNumber:
|
||||
print("Too large")
|
||||
else:
|
||||
print("You've got it in", count, "tries!")
|
||||
break
|
|
@ -0,0 +1,69 @@
|
|||
# 插入
|
||||
print('插入'*15)
|
||||
x = [1,2,3]
|
||||
print(x)
|
||||
x = x+ [4]
|
||||
x.append(5)
|
||||
print(x)
|
||||
x.insert(3,'w')
|
||||
x.extend(['a','b'])
|
||||
print(x*3)
|
||||
|
||||
# 删除
|
||||
print("删除"*15)
|
||||
y = ["a","b","c","d",'e','f']
|
||||
del y[2]
|
||||
print(y)
|
||||
y.pop(0)
|
||||
print(y)
|
||||
y.remove('f')
|
||||
print(y)
|
||||
|
||||
# 列表元素访问与计数
|
||||
print("列表元素访问与计数"*5)
|
||||
x =[1,2,3,3,4,5]
|
||||
print(x.count(3),x.index(2))
|
||||
|
||||
# 列表排序
|
||||
print("列表排序"*10)
|
||||
x = [1,2,4,5,6,34,22,55,22,11,24,56,78]
|
||||
import random as r
|
||||
r.shuffle(x)
|
||||
print(x)
|
||||
x.reverse()
|
||||
print("reverse",x)
|
||||
x.sort(reverse = True)
|
||||
print('sort ',x)
|
||||
# 使用内置函数sorted对列表进行排序并返回新列表,不对原列表做任何修改。
|
||||
sorted(x)
|
||||
reversed(x)
|
||||
|
||||
# 打包
|
||||
print("打包"*10)
|
||||
a = [1,2,3]
|
||||
b = [4,5,6]
|
||||
print(list(zip(a,b)))
|
||||
|
||||
# 枚举
|
||||
print("枚举"*10)
|
||||
for item in enumerate('abcdef'):
|
||||
print(item)
|
||||
|
||||
# 遍历列表的三种方式
|
||||
print("遍历列表的三种方式"*10)
|
||||
a = ['a','b','c','d','e','f']
|
||||
for i in a:
|
||||
print(i)
|
||||
for i in range(len(a)):
|
||||
print(i,a[i])
|
||||
for i,ele in enumerate(a):
|
||||
print(i,ele)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
# 列表推导式
|
||||
|
||||
x = [[1,2,3], [4,5,6], [7,8,9]]
|
||||
y = [num for i in x for num in i]
|
||||
print(y)
|
||||
y = []
|
||||
for i in x:
|
||||
for num in i:
|
||||
y.append(num)
|
||||
print(y)
|
||||
# 过滤不符合条件的元素 从列表中选择符合条件的元素组成新的列表
|
||||
print('过滤不符合条件的元素 从列表中选择符合条件的元素组成新的列表'.center(50,'*'))
|
||||
x = [-1,-4,6,7.5,-2.3,9,-11]
|
||||
y = [i for i in x if i>0]
|
||||
print(y)
|
||||
|
||||
x = [(x, y) for x in range(3) for y in range(3)]
|
||||
print(x)
|
||||
x = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
|
||||
print(x)
|
||||
|
||||
# 列表综合练习 写一个循环,不断的问用户想买什么,用户选择一个商品编号,
|
||||
# 就把对应的商品添加到购物车里,最终用户输入q退出时,打印购物车里的商品列表
|
||||
l1 = [['a',23],['b',34],['c',33],['d',345]]
|
||||
l2 = []
|
||||
print("商品列表****************")
|
||||
for (index, i) in enumerate(l1):
|
||||
print("商品{},价格为{}", index, i)
|
||||
while True:
|
||||
|
||||
choise = input("请输入你选择的商品编号:")
|
||||
if choise.isdigit():
|
||||
if int(choise) in range(len(l1)) :
|
||||
print("你选择的是{}".format(choise))
|
||||
l2.append(l1[int(choise)])
|
||||
print(l2)
|
||||
else:
|
||||
print("你选的商品不在列表中")
|
||||
elif choise == 'q':
|
||||
break
|
||||
|
||||
if len(l2)>0:
|
||||
print("你选的商品如下:")
|
||||
for index,i in enumerate(l2):
|
||||
print("商品编号{},商品名称{},商品价格{}".format(index,i[0],i[1]))
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
li = ['a','b','c','d','e']
|
||||
#index 0 1 2 3 4
|
||||
#index -5 -4 -3 -2 -1
|
||||
print(li[0:1])
|
||||
print(li[2:])
|
||||
print(li[::2])
|
||||
|
||||
print(li[:-2])
|
||||
print(li[::-1])
|
||||
|
||||
# 在尾部最佳
|
||||
li[len(li):]=[9]
|
||||
# 删除前2个元素
|
||||
li[:2] = []
|
||||
print(li)
|
||||
|
||||
# 删除偶数位置上的元素
|
||||
li = ['a','b','c','d','e']
|
||||
del li[::2]
|
||||
print(li)
|
||||
|
||||
# 切片,浅复制
|
||||
x = li[::]
|
|
@ -1,9 +1,8 @@
|
|||
|
||||
a_num = [0.01,"zhangsan",[1,2,3]]
|
||||
a_num+=[2]
|
||||
print(a_num)
|
||||
print(a_num*2)
|
||||
# 使用列表的pop()方法删除并返回指定(默认为最后一个)位置上的元素,如果给定的索引超出了列表的范围则抛出异常。
|
||||
print("使用列表的pop()方法删除并返回指定(默认为最后一个)位置上的元素,如果给定的索引超出了列表的范围则抛出异常。")
|
||||
print(a_num.pop())
|
||||
print(a_num.pop(1))
|
||||
print(a_num)
|
|
@ -0,0 +1,9 @@
|
|||
x = (1,2,3)
|
||||
|
||||
x =(3)
|
||||
print(type(x))
|
||||
x =(3,)
|
||||
print(type(x))
|
||||
# 使用tuple函数将其他序列转换为元组
|
||||
print(tuple(range(5)))
|
||||
print(tuple('abcdefg'))
|
|
@ -0,0 +1,16 @@
|
|||
# 1.有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前20项之和。
|
||||
from functools import reduce
|
||||
# A 构建list
|
||||
a = 2
|
||||
b = 1
|
||||
l = [a/b]
|
||||
for i in range(1,20):
|
||||
a,b = a+b,a
|
||||
l.append(a/b)
|
||||
print(reduce(lambda x,y:x+y,l))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
# 2.给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
|
||||
x = int(input())
|
||||
y = list(str(x))
|
||||
print(len(y))
|
||||
y.reverse()
|
||||
print(y)
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
# 3.有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),
|
||||
# 凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
|
||||
|
||||
list = [i for i in range(1,200)]
|
||||
print(list)
|
||||
|
||||
while True:
|
||||
list.pop(2)
|
||||
before = list[:2]
|
||||
list = list[2:]
|
||||
list.extend(before)
|
||||
if list.__len__()<=2:
|
||||
break
|
||||
print(list)
|
|
@ -0,0 +1,19 @@
|
|||
# 4.题:编写一个程序,根据控制台输入的事务日志计算银行帐户的净金额。 事务日志格式如下所示: D 100 W 200
|
||||
# D表示存款,而W表示提款。 假设为程序提供了以下输入: D 300 D 300 W 200 D 100 然后,输出应该是: 500
|
||||
|
||||
netAmount = 0
|
||||
while True:
|
||||
print("请输入:")
|
||||
s = input()
|
||||
if not s:
|
||||
break
|
||||
values = s.split(" ")
|
||||
operation = values[0]
|
||||
amount = int(values[1])
|
||||
if operation=="D":
|
||||
netAmount+=amount
|
||||
elif operation=="W":
|
||||
netAmount-=amount
|
||||
else:
|
||||
pass
|
||||
print (netAmount)
|
|
@ -0,0 +1,30 @@
|
|||
# 5.机器人从原点(0,0)开始在平面中移动。 机器人可以通过给定的步骤向上,向下,向左和向右移动。
|
||||
# 机器人运动的痕迹如下所示: UP 5 DOWN 3 LETF 3 RIGHT 2 方向之后的数字是步骤。
|
||||
# 请编写一个程序来计算一系列运动和原点之后距当前位置的距离。
|
||||
# 如果距离是浮点数,则只打印最接近的整数。
|
||||
# 例:如果给出以下元组作为程序的输入:
|
||||
# UP 5 DOWN 3 LETF 3 RIGHT 2 然后,程序的输出应该是:2
|
||||
|
||||
import math
|
||||
|
||||
pos = [0, 0]
|
||||
print("请输入:")
|
||||
while True:
|
||||
s = input()
|
||||
if not s:
|
||||
break
|
||||
movement = s.split(" ")
|
||||
direction = movement[0]
|
||||
steps = int(movement[1])
|
||||
if direction == "UP":
|
||||
pos[0] += steps
|
||||
elif direction == "DOWN":
|
||||
pos[0] -= steps
|
||||
elif direction == "LEFT":
|
||||
pos[1] -= steps
|
||||
elif direction == "RIGHT":
|
||||
pos[1] += steps
|
||||
else:
|
||||
pass
|
||||
|
||||
print(int(round(math.sqrt(pos[1] ** 2 + pos[0] ** 2))))
|
|
@ -0,0 +1,69 @@
|
|||
# 1.地铁站编号和站名对应关系如下: 1=朱辛庄 2=育知路 3=平西府 4=回龙观东大街 5=霍营 //....
|
||||
#
|
||||
# 遍历打印(可以不按顺序打印): 第10站: 森林公园南门 第6站: 育新 第12站: 奥体中心 第13站: 北土城 //...
|
||||
#
|
||||
# 2.计算地铁票价规则: 总行程 3站内(包含3站)收费3元, 3站以上但不超过5站(包含5站)的收费4元, 5站以上的,在4元的基础上,每多1站增加2元, 10元封顶;
|
||||
#
|
||||
# 3.打印格式(需要对键盘录入的上车站和到达站进行判断,如果没有该站,提示重新输入,直到站名存在为止): 注意:每站需要2分钟 请输入上车站: 沙河 您输入的上车站:沙河不存在,请重新输入上车站: 上地 您输入的上车站:上地不存在,请重新输入上车站: 朱辛庄 请输入到达站: 沙河 您输入的到达站:沙河不存在,请重新输入到达站: 西二旗 您输入的到达站:西二旗不存在,请重新输入到达站: 西小口 从朱辛庄到西小口共经过6站收费6元,大约需要 12分钟
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
st = """十三号街站 05:30 23:00 —— ——
|
||||
中央大街站 05:31 23:01 06:28 23:47
|
||||
七号街站 05:33 23:03 06:26 23:45
|
||||
四号街站 05:36 23:06 06:24 23:42
|
||||
张士站 05:38 23:08 06:21 23:40
|
||||
开发大道站 05:41 23:11 06:19 23:37
|
||||
于洪广场站 05:43 23:13 06:16 23:35
|
||||
迎宾路站 05:46 23:16 06:14 23:33
|
||||
重工街站 05:48 23:18 06:11 23:30
|
||||
启工街站 05:51 23:21 06:09 23:28
|
||||
保工街站 05:53 23:23 06:07 23:26
|
||||
铁西广场站 05:55 23:25 06:04 23:23
|
||||
云峰北街站 05:58 23:28 06:02 23:21
|
||||
沈阳站 06:01 23:31 06:00 23:18
|
||||
太原街站 06:03 23:33 06:16 23:16
|
||||
南市场站 06:05 23:35 06:13 23:13
|
||||
青年大街站 06:07 23:37 06:11 23:11
|
||||
怀远门站 06:10 23:40 06:09 23:09
|
||||
中街站 06:13 23:43 06:06 23:06
|
||||
东中街站 06:15 23:45 06:04 23:04
|
||||
滂江街站 06:17 23:47 06:01 23:01
|
||||
黎明广场站 —— —— 06:00 23:00"""
|
||||
lst = st.split()
|
||||
|
||||
llsstt = list(filter(lambda x : '站' in x,lst))
|
||||
print(llsstt)
|
||||
|
||||
while True:
|
||||
upstation = input('请输入上车站:')
|
||||
if upstation not in llsstt:
|
||||
print(f'您输入的上车站:{upstation}不存在,请重新输入上车站')
|
||||
|
||||
upstation_idx = llsstt.index(upstation)
|
||||
|
||||
downstation = input('请输入下车站:')
|
||||
if downstation not in llsstt:
|
||||
print(f'您输入的下车站:{upstation}不存在,请重新输入下车站')
|
||||
else:
|
||||
downstation_idx = llsstt.index(downstation)
|
||||
if downstation_idx < upstation_idx:
|
||||
print('下车站必须在上车站之后')
|
||||
else:
|
||||
break
|
||||
|
||||
diff = downstation_idx - upstation_idx
|
||||
price = 0
|
||||
if diff <= 3:
|
||||
price = 3
|
||||
elif diff <= 5:
|
||||
price = 4
|
||||
else:
|
||||
price = 4 + (diff - 5)*2
|
||||
|
||||
if price > 10:
|
||||
price = 10
|
||||
|
||||
print(f'从{upstation}到{downstation}共经过{diff}站收费{price}元,大约需要{diff*2}分钟')
|
|
@ -0,0 +1,34 @@
|
|||
|
||||
|
||||
from functools import reduce
|
||||
lst=[1,2,3,4]
|
||||
print(reduce(lambda x,y: x*y+1, lst))
|
||||
|
||||
#计算过程如下:
|
||||
# 这个式子只有两个参数,没有初始化值,那么就取列表前2项,通过lambda函数计算结果
|
||||
#1*2+1=3,
|
||||
#上面计算的结果在与列表第三个元素通过lambda函数计算
|
||||
# 3*3+1=10
|
||||
#上面计算的结果在与列表第四个元素通过lambda函数计算
|
||||
# 10*4+1=41
|
||||
|
||||
from functools import reduce
|
||||
lst=[1,2,3,4]
|
||||
print(reduce(lambda x,y: x+y, lst,5))
|
||||
|
||||
# 5是初始值,也可以理解为第三个参数
|
||||
# 计算呢过程
|
||||
# -->5+1=6
|
||||
# -->6+2=8
|
||||
# -->8+3=11
|
||||
# -->11+4=15
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
x = int(input("输入5位正整数"))
|
||||
print(list(str(x)))
|
||||
|
||||
|
||||
23456
|
|
@ -0,0 +1,47 @@
|
|||
# strip 默认去除字符前后两端的空格, 换行符, tab
|
||||
ss = ' qqwalex qqwusir barryy'
|
||||
s = ss.strip()
|
||||
print(s)
|
||||
print(s.strip('qqw'))
|
||||
print(s.strip(''))
|
||||
print(s.lstrip('yy'))
|
||||
print(s.rstrip('yy'))
|
||||
|
||||
# split 把字符串分割成列表
|
||||
#### 分割出的元素比分隔符数+1 ***
|
||||
#### 字符串变成->>>列表
|
||||
s = 'qqwalex qqwusir barryy'
|
||||
s1 = 'qqwale;x qqwu;sir bar;ryy'
|
||||
print(s.split()) #### 默认以空格分割
|
||||
print(s1.split(';')) #### 以指定字符分割
|
||||
print(s1.split(';', 1)) #### 指定分割多少个
|
||||
|
||||
# join把列表转化成字符串
|
||||
#### 列表转化成字符串 list --> str
|
||||
s = 'alex'####看成字符列表
|
||||
li = ['aa', 'ddj', 'kk'] #### 必须全是字符串
|
||||
s1 = '_'.join(s)
|
||||
print(s1)
|
||||
s2 = ' '.join(li)
|
||||
print(s2)
|
||||
|
||||
#### count 计算字符串中某个字符出现的次数 ***
|
||||
s = 'www.neuedu.com'
|
||||
print(s.count('u'))
|
||||
print(s.count('u', 7))
|
||||
|
||||
#### format 格式化输出 ***
|
||||
#### 第一种方式:
|
||||
s = '我叫{}, 今年{}, 性别{}'.format('小五', 25, '女')
|
||||
print(s)
|
||||
#### 第二种方式
|
||||
s1 = '我叫{0}, 今年{1}, 性别{2},我依然叫{0}'.format('小五', 25, '女')
|
||||
print(s1)
|
||||
#### 第三种方式
|
||||
s2 = '我叫{name}, 今年{age}, 性别{sex},我依然叫{name}'.format(age=25, sex='女',name='小五')
|
||||
print(s2)
|
||||
# 字符串是不可变变量,不支持直接通过下标修改
|
||||
msg = 'abcdefg'
|
||||
# msg[2] = 'z'
|
||||
msg = msg[:2] + 'z' + msg[3:]
|
||||
print(msg)
|
|
@ -0,0 +1,60 @@
|
|||
value = [1, 2, 3, 4, 5]
|
||||
key = ['a', 'b', 'c', 'd', 'e']
|
||||
|
||||
# 以给定内容为键,创建值为空的字典
|
||||
dic = dict.fromkeys(key)
|
||||
print(dic)
|
||||
|
||||
# 使用dict()根据给定的键、值创建字典
|
||||
dic = dict(name = 'aa',age = 23)
|
||||
print (dic)
|
||||
|
||||
# zip创建字典
|
||||
dic = dict(zip(key, value))
|
||||
print(dic)
|
||||
|
||||
# 读取字典内容
|
||||
print(dic.get('a'),dic['a'])
|
||||
|
||||
# 字典中定义其它类型数据
|
||||
dic['a']= []
|
||||
dic['a'].append(12)
|
||||
dic['a'].append(13)
|
||||
|
||||
print(dic.get('a'),dic)
|
||||
|
||||
# 遍历字典
|
||||
print('遍历字典'.center(50,'*'))
|
||||
for i in dic.items():
|
||||
print (i)
|
||||
for i,j in zip(dic.keys(),dic.values()):
|
||||
print(i,dic[i],j)
|
||||
|
||||
|
||||
|
||||
# 增加新元素 与更新 与删除
|
||||
print('增加新元素'.center(50,'*'))
|
||||
dic.setdefault('dd',12)
|
||||
print(dic)
|
||||
dic['cc']=22
|
||||
print(dic)
|
||||
dic.update({'dd':13,'ee':[11,22,33,44]})
|
||||
print(dic)
|
||||
dic.pop('dd')
|
||||
print(dic)
|
||||
|
||||
|
||||
# 字典popitem()方法作用是:随机返回并删除字典中的一对键和值(项)。
|
||||
# 为什么是随机删除呢?因为字典是无序的,没有所谓的“最后一项”或是其它顺序。
|
||||
# 在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高。
|
||||
for i in range(7):
|
||||
dic.popitem()
|
||||
print(dic)
|
||||
|
||||
# 有序字典
|
||||
print('有序字典'.center(50,'*'))
|
||||
import collections
|
||||
dic = collections.OrderedDict()
|
||||
dic = {'a':1,'b':2,'c':3}
|
||||
print(dic)
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
value = [1, 2, 3, 4, 5]
|
||||
key = ['a', 'b', 'c', 'd', 'e']
|
||||
|
||||
dic = {k:v for k,v in zip(key,value)}
|
||||
print(dic)
|
||||
|
||||
dic = {k:v+1 for v,k in enumerate(key)}
|
||||
print(dic)
|
||||
|
||||
dic = {key[i]:value[i] for i in range(len(key))}
|
||||
print(dic)
|
|
@ -0,0 +1,22 @@
|
|||
# 集合是无序可变序列,使用一对大括号界定,元素不可重复,同一个集合中每个元素都是唯一的。
|
||||
# 集合中只能包含数字、字符串、元组等不可变类型的数据,而不能包含列表、字典、集合等可变类型的数据。
|
||||
|
||||
cl = {1,2,3,4}
|
||||
cl.add(5)
|
||||
print(cl)
|
||||
|
||||
cl = set(range(1,15))
|
||||
print(cl)
|
||||
|
||||
li = [i for i in range(1,10)]
|
||||
li.append(1)
|
||||
li.append(2)
|
||||
print(li)
|
||||
|
||||
cl = set(li)
|
||||
print(cl)
|
||||
|
||||
cl.update({44,55,'a'})
|
||||
print(cl)
|
||||
cl.remove('a')
|
||||
print(cl)
|
|
@ -0,0 +1,8 @@
|
|||
cl1 = {i for i in range(1,10)}
|
||||
cl2 = {i for i in range(5,15)}
|
||||
|
||||
|
||||
print(cl1,cl2)
|
||||
print(cl1 | cl2)
|
||||
print(cl1 & cl2)
|
||||
print(cl1 - cl2)
|
|
@ -0,0 +1,12 @@
|
|||
import random
|
||||
|
||||
li = [random.randint(1,10) for i in range(10)]
|
||||
print(li)
|
||||
|
||||
norepeat = []
|
||||
for i in li:
|
||||
if i not in norepeat:
|
||||
norepeat.append(i)
|
||||
print(norepeat)
|
||||
print(set(norepeat))
|
||||
print(set(li))
|
|
@ -0,0 +1,12 @@
|
|||
import random
|
||||
|
||||
li = [random.randint(1,10) for i in range(10)]
|
||||
print(li)
|
||||
|
||||
norepeat = []
|
||||
for i in li:
|
||||
if i not in norepeat:
|
||||
norepeat.append(i)
|
||||
print(norepeat)
|
||||
print(set(norepeat))
|
||||
print(set(li))
|
|
@ -0,0 +1,29 @@
|
|||
word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."
|
||||
word = word.replace('.','').replace(',','')
|
||||
li = word.split()
|
||||
print(li)
|
||||
|
||||
# 第一种方法:
|
||||
key = set(li)
|
||||
value = [0 for i in range(len(key))]
|
||||
dic = {k:v for k,v in zip(key,value)}
|
||||
print(dic)
|
||||
|
||||
for i in dic:
|
||||
for j in li:
|
||||
if i == j:
|
||||
dic[i]+=1
|
||||
continue
|
||||
print(dic)
|
||||
|
||||
# 第二种方法:
|
||||
s =set(li)
|
||||
for i in s:
|
||||
count=word.count(i)
|
||||
print(i,'出现次数:',count)
|
||||
|
||||
# 第三种方法:
|
||||
dict = {}
|
||||
for key in li:
|
||||
dict[key] = dict.get(key,0) + 1
|
||||
print(dic)
|
|
@ -0,0 +1,27 @@
|
|||
# 已知有十六支男子足球队参加2008 北京奥运会。写一个程序,把这16 支球队随机分为4 个组。采用List集合和随机数
|
||||
# 2008 北京奥运会男足参赛国家:
|
||||
# 科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚,日本,美国,中国,新西兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利
|
||||
# 提示:分配一个,删除一个
|
||||
# // key保存的是第几组,value是该组对应的国家集合
|
||||
# // map,保存最终分组结果
|
||||
import random
|
||||
dic = {}
|
||||
country = "科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚,日本,美国,中国,新西兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利"
|
||||
country = country.split(',')
|
||||
print (country)
|
||||
|
||||
# 方法1
|
||||
import random
|
||||
value = [i for i in range(1,len(country))]
|
||||
random.shuffle(value)
|
||||
print(value)
|
||||
dic = {k:v for k,v in zip(country,value)}
|
||||
map = {}
|
||||
for i in range(1,5):
|
||||
li = []
|
||||
for j in range(4):
|
||||
index = random.randint(0,len(country)-1)
|
||||
li.append(country[index])
|
||||
country.remove(country[index])
|
||||
map[i] = li
|
||||
print(map)
|
|
@ -0,0 +1,7 @@
|
|||
def add(*aa,sum1 = 1):
|
||||
sum = 0
|
||||
for i in aa:
|
||||
sum+=i
|
||||
return sum+sum1
|
||||
|
||||
print(add(2,3,4,12))
|
|
@ -0,0 +1,25 @@
|
|||
# 加了星号(*)的变量名会存放所有未命名的变量参数。而加(**)的变量名会存放命名的变量参数
|
||||
def print_info(**kwargs):
|
||||
print(kwargs)
|
||||
for i in kwargs:
|
||||
print('%s:%s'%(i,kwargs[i]))#根据参数可以打印任意相关信息了
|
||||
return
|
||||
print_info(name='alex',age=18,sex='female',hobby='girl',nationality='Chinese',ability='Python')
|
||||
|
||||
def print_info(name,*args,**kwargs):#def print_info(name,**kwargs,*args):报错
|
||||
print('Name:%s'%name)
|
||||
print('args:',args)
|
||||
print('kwargs:',kwargs)
|
||||
return
|
||||
print_info('alex',18,17,'dfgdfg',hobby='girl',nationality='Chinese',ability='Python')
|
||||
# print_info(hobby='girl','alex',18,nationality='Chinese',ability='Python') #报错
|
||||
#print_info('alex',hobby='girl',18,nationality='Chinese',ability='Python') #报错
|
||||
|
||||
def f(*args):
|
||||
print(args)
|
||||
|
||||
f(*[1,2,5])
|
||||
|
||||
def f(**kargs):
|
||||
print(kargs)
|
||||
f(**{'name':'alex'})
|
|
@ -0,0 +1,21 @@
|
|||
# 接受一个或多个函数作为输入 输出一个函数
|
||||
def add(x, y, f):
|
||||
return f(x) + f(y)
|
||||
|
||||
res = add(3, -6, abs)
|
||||
print(res)
|
||||
|
||||
|
||||
def method():
|
||||
x = 2
|
||||
|
||||
def double(n):
|
||||
return n * x
|
||||
|
||||
return double
|
||||
|
||||
|
||||
fun = method()
|
||||
num = fun(20)
|
||||
print(num)
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
# global关键字声明的变量必须在全局作用域上,不能嵌套作用域上,
|
||||
# 当要修改嵌套作用域(enclosing作用域,外层非全局作用域)中的变量怎么办呢,这时就需要nonlocal关键字了
|
||||
def outer():
|
||||
count = 10
|
||||
def inner():
|
||||
# nonlocal count
|
||||
# global count
|
||||
count = 100
|
||||
print(count)
|
||||
inner()
|
||||
print(count)
|
||||
outer()
|
||||
|
||||
# 当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal关键字了,
|
||||
# 当修改的变量是在全局作用域(global作用域)上的,就要使用global先声明一下
|
|
@ -0,0 +1,11 @@
|
|||
# 关键字lambda表示匿名函数,冒号前面的n表示函数参数,可以有多个参数。
|
||||
#
|
||||
# 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
|
||||
#
|
||||
# 用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
|
||||
#
|
||||
# 有些函数在代码中只用一次,而且函数体比较简单,使用匿名函数可以减少代码量,看起来比较"优雅“
|
||||
|
||||
a = lambda x,y,z:x*x+y*y+z*z if x>0 and y>0 and z>0 else -x*x-y*y-z*z
|
||||
# 函数名 参数:返回值
|
||||
print(a(-2,-3,-4))
|
|
@ -0,0 +1,56 @@
|
|||
# map()函数接收两个参数,一个是函数,
|
||||
# 一个是Iterable,map将传入的函数依次作用到序列的每个元素,
|
||||
# 并把结果作为新的Iterator返回
|
||||
|
||||
# 例1 求列表[1,2,3,4,5,6,7,8,9],返回一个n*n 的列表
|
||||
|
||||
#一般解决方案
|
||||
li = [1,2,3,4,5,6,7,8,9]
|
||||
for ind,val in enumerate(li):
|
||||
li[ind] = val * val
|
||||
print(li)
|
||||
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
|
||||
|
||||
# 高级解决方案
|
||||
li = [1,2,3,4,5,6,7,8,9]
|
||||
print(list(map(lambda x:x*x,li)))
|
||||
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
|
||||
|
||||
|
||||
#接受一个list并利用reduce()求积
|
||||
from functools import reduce
|
||||
li = [1,2,3,4,5,6,7,8,9]
|
||||
print(reduce(lambda x,y:x * y,li))
|
||||
# 结果=1*2*3*4*5*6*7*8*9 = 362880
|
||||
|
||||
# 在一个list中,删掉偶数,只保留奇数
|
||||
li = [1, 2, 4, 5, 6, 9, 10, 15]
|
||||
print(list(filter(lambda x:x % 2==1,li))) # [1, 5, 9, 15]
|
||||
|
||||
# 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数
|
||||
li = list(range(1, 200))
|
||||
print(list(filter(lambda x:int(str(x))==int(str(x)[::-1]),li)))
|
||||
|
||||
# 对列表按照绝对值进行排序
|
||||
li= [-21, -12, 5, 9, 36]
|
||||
print(sorted(li, key = lambda x:abs(x)))
|
||||
# [5, 9, -12, -21, 36]
|
||||
|
||||
# 把下面单词以首字母排序
|
||||
li = ['bad', 'about', 'Zoo', 'Credit']
|
||||
print(sorted(li, key = lambda x : x[0]))
|
||||
# 输出['Credit', 'Zoo', 'about', 'bad']
|
||||
"""
|
||||
对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面。
|
||||
"""
|
||||
|
||||
# 假设我们用一组tuple表示学生名字和成绩:
|
||||
|
||||
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
|
||||
# 请用sorted()对上述列表分别按名字排序
|
||||
print(sorted(L, key = lambda x : x[0]))
|
||||
# 输出[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
|
||||
|
||||
# 再按成绩从高到低排序
|
||||
print(sorted(L, key = lambda x : x[1], reverse=True))
|
||||
# 输出[('Adam', 92), ('Lisa', 88), ('Bob', 75), ('Bart', 66)]
|
|
@ -1,6 +0,0 @@
|
|||
x = (1,2,3)
|
||||
|
||||
x =(3)
|
||||
print(type(x))
|
||||
x =(3,)
|
||||
print(type(x))
|
|
@ -1,11 +0,0 @@
|
|||
# 列表切片
|
||||
|
||||
colors=["red","blue","green"]
|
||||
|
||||
colors[0] =="red"
|
||||
colors[-1]=="green"
|
||||
colors[1]=="blue"
|
||||
|
||||
aList = [3,5,7,9,11]
|
||||
del aList[:3]
|
||||
print(aList)
|
|
@ -1,42 +0,0 @@
|
|||
aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]
|
||||
import random
|
||||
random.shuffle(aList) #随机降序
|
||||
|
||||
print(aList)
|
||||
aList.sort() #默认是升序排序
|
||||
aList.sort(reverse = True) #降序排序
|
||||
print(aList)
|
||||
|
||||
|
||||
# 返回可迭代的zip对象
|
||||
aList = [1, 2, 3]
|
||||
bList = [4, 5, 6]
|
||||
cList = zip(aList, bList)
|
||||
print(list(cList))
|
||||
|
||||
# enumerate()
|
||||
for item in enumerate('abcdef'):
|
||||
print(item)
|
||||
|
||||
# 遍历列表的三种方式
|
||||
a = ['a','b','c','d','e','f']
|
||||
for i in a:
|
||||
print(i)
|
||||
for i in range(len(a)):
|
||||
print(i,a[i])
|
||||
for i,ele in enumerate(a):
|
||||
print("0000000 ",i,ele)
|
||||
|
||||
# 列表推导式
|
||||
lis = [i for i in range(100)]
|
||||
print(lis)
|
||||
|
||||
# 使用列表推导式实现嵌套列表的平铺
|
||||
vec = [[1,2,3], [4,5,6], [7,8,9]]
|
||||
lis = [num for elem in vec for num in elem]
|
||||
print ("1111111111 ",lis)
|
||||
|
||||
# 过滤不符合条件的元素 从列表中选择符合条件的元素组成新的列表
|
||||
aList = [-1,-4,6,7.5,-2.3,9,-11]
|
||||
lis = [i for i in aList if i>0]
|
||||
print ("2222222222 ",lis)
|
|
@ -1,56 +0,0 @@
|
|||
a_dict = {'server': 'db.neuedu.com', 'database': 'mysql'}
|
||||
# 使用dict()利用已有数据创建字典
|
||||
keys = ['a', 'b', 'c', 'd']
|
||||
values = [1, 2, 3, 4]
|
||||
dictionary = dict(zip(keys, values))
|
||||
print(dictionary)
|
||||
|
||||
x = dict() #空字典
|
||||
# 使用dict()根据给定的键、值创建字典
|
||||
d = dict(name='Dong', age=37)
|
||||
print(d)
|
||||
|
||||
# 以给定内容为键,创建值为空的字典
|
||||
adict = dict.fromkeys(['name', 'age', 'sex'])
|
||||
print(adict,adict['name'])
|
||||
|
||||
# 使用字典对象的items()方法可以返回字典的键、值对列表
|
||||
aDict={'name':'Dong', 'sex':'male', 'age':37}
|
||||
|
||||
# 使用字典对象的keys()方法可以返回字典的键列表
|
||||
for item in aDict.items():
|
||||
print(item)
|
||||
print(aDict.keys(),aDict.values())
|
||||
|
||||
# 使用字典对象的setdefault()方法返回指定“键”对应的“值”,如果字典中不存在该“键”,就添加一个新元素并设置该“键”对应的“值”。
|
||||
aDict ={'name' : 'Wang','sex' : 'male'}
|
||||
aDict.setdefault('age','28') #增加新元素
|
||||
aDict['address'] = 'SDIBT' #增加新元素
|
||||
print(aDict)
|
||||
|
||||
# 使用字典对象的update方法将另一个字典的键、值对添加到当前字典对象
|
||||
aDict = {'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
|
||||
print(aDict.items())
|
||||
aDict.update({'a':'a','b':'b'})
|
||||
print(aDict)
|
||||
|
||||
# 判断一个key是否在字典中
|
||||
d = {'name':'tom', 'age':10, 'Tel':110}
|
||||
print ('name' in d.keys())
|
||||
print ('name' in d)
|
||||
|
||||
# 无序字典
|
||||
x = dict()
|
||||
x['a'] = 3
|
||||
x['b'] = 5
|
||||
x['c'] = 8
|
||||
|
||||
# 有序字典
|
||||
import collections
|
||||
x = collections.OrderedDict()
|
||||
|
||||
|
||||
# 字典pop()方法
|
||||
x = {'a':1,'b':2}
|
||||
x.pop('a')
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
# 例1
|
||||
strings = ['import','is','with','if','file','exception','liuhu']
|
||||
d = {key: val for val,key in enumerate(strings)}
|
||||
# 用字典推导式以字符串以及其长度位置建字典
|
||||
s = {strings[i]: len(strings[i]) for i in range(len(strings))}
|
||||
k = {k:len(k)for k in strings} #相比上一个写法简单很多
|
||||
print(d)
|
||||
# {'import': 0, 'is': 1, 'with': 完整例子, 'if': 3, 'file': 4, 'exception': 5, 'liuhu': 6}
|
||||
print(s)
|
||||
# {'import': 6, 'is': 完整例子, 'with': 4, 'if': 完整例子, 'file': 4, 'exception': 9, 'liuhu': 5}
|
||||
print(k)
|
||||
# {'import': 6, 'is': 完整例子, 'with': 4, 'if': 完整例子, 'file': 4, 'exception': 9, 'liuhu': 5}
|
||||
|
||||
# 例2
|
||||
mc = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
|
||||
mca = {k.lower(): mc.get(k.lower(), 0) + mc.get(k.upper(), 0) for k in mc.keys()}
|
||||
|
||||
# mcase_frequency == {'a': 17, 'z': 3, 'b': 34} she
|
|
@ -1,43 +0,0 @@
|
|||
# 集合的创建
|
||||
a_set = set(range(8,14))
|
||||
#自动去除重复
|
||||
b_set = set([0, 1, 2, 3, 0, 1, 2, 3, 7, 8])
|
||||
#空集合
|
||||
c_set = set()
|
||||
|
||||
# 集合元素的增加与删除
|
||||
s = {1,2,3}
|
||||
s.add(3)
|
||||
s.update({3,4,5})
|
||||
s.remove(3)
|
||||
print(s)
|
||||
|
||||
# 集合操作
|
||||
a_set = set([8, 9, 10, 11, 12, 13])
|
||||
b_set = {0, 1, 2, 3, 7, 8}
|
||||
# 并集
|
||||
print(a_set | b_set,a_set.union(b_set) )
|
||||
#交集
|
||||
print(a_set & b_set,a_set.intersection(b_set) )
|
||||
#差集
|
||||
print(a_set.difference(b_set),a_set - b_set)
|
||||
|
||||
# 测试是否为子集
|
||||
x = {1, 2, 3}
|
||||
y = {1, 2, 5}
|
||||
z = {1, 2, 3, 4}
|
||||
print(x.issubset(y),x.issubset(z))
|
||||
|
||||
# 使用集合快速提取序列中单一元素
|
||||
import random
|
||||
listRandom = [random.choice(range(500)) for i in range(100)]
|
||||
noRepeat = []
|
||||
for i in listRandom :
|
||||
if i not in noRepeat :
|
||||
noRepeat.append(i)
|
||||
print(len(listRandom),len(noRepeat))
|
||||
newSet = set(listRandom)
|
||||
|
||||
# 集合推导式
|
||||
s = {x.strip() for x in (' he ', 'she ', ' I')}
|
||||
print(s)
|
Loading…
Reference in New Issue