1、例子
for i in range(1, 10): # 控制行 i [1~9]
line = ''
for j in range(1, i+1): # 控制列 j [1~9] 1<=j<=i
line += '{0}*{1}={2:<2} '.format(j, i, i*j) # :<2 冒号是分隔符,<表示左对齐,2表示宽度
print(line)
for i in range(1, 10):
line = ''
for j in range(1, i+1):
line += '{}*{}={:<{}}'.format(j, i, i*j, 3 if j < 4 else 3) # line = line + $line
print('{:>66}'.format(line)) # :>右对齐
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=1
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
for i in range(1, 10):
line = ''
for j in range(i, 10):
line += '{}*{}={:<{}}'.format(i, j, i*j, 2 if j < 4 else 3)
print('{:>66}'.format(line))
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9
2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18
3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27
4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36
5*5=25 5*6=30 5*7=35 5*8=40 5*9=45
6*6=36 6*7=42 6*8=48 6*9=54
7*7=49 7*8=56 7*9=63
8*8=64 8*9=72
9*9=81
user = 'tom'
passwd = 'tom'
flag = False
for i in range(3):
u = input('username = ')
p = input('passwd = ')
if user == u and passwd == p:
flag = True
break
print('Invalid username or passwd')
if not flag:
print('failed')
else:
print('login successful!')
Invalid username or passwd
Invalid username or passwd
login successful!
f1, f2 = 0, 1
count = 1
print(count, f2)
while True:
# fn = f1 + f2
count += 1
if count > 10:
break
# f1 = f2
# f2 = fn
f1, f2 = f2, f1 + f2
print(count, f2)
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
n = 7
e = n // 2
for i in range(-e, e+1):
# if i < 0:
# print(' '* -i, end='')
# print('*' * (n - 2 * -i))
# else:
# print(' '* i, end='')
# print('*' * (n - 2 * i))
print(" " * abs(i), '*' * (n -2 * abs(i)), sep='')
*
***
*****
*******
*****
***
*
n = 15
e = n // 2
for i in range(-e, e+1):
print("{:#^{}}".format('*' * (n - 2 * abs(i)), n)) # ^ 居中
#######*#######
######***######
#####*****#####
####*******####
###*********###
##***********##
#*************#
***************
#*************#
##***********##
###*********###
####*******####
#####*****#####
######***######
#######*#######
# 编写一个函数,接收一个参数n,n为正整数,上下三角两种打印方式,要求数字必须对齐
def triangle_print(n):
for i in range(1, n+1):
for j in range(n, 0, -1):
if j >= i:
print(j, end=' ')
print()
#
triangle_print(5)
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
def triangle_print(n):
for i in range(1, n+1):
for j in range(n, 0, -1):
if j <= i:
print(j, end=' ')
else:
pass
print()
#
triangle_print(12)
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
def triangle_print(n):
for i in range(1, n+1):
for j in range(n, 0, -1):
if j <= i:
print(j, end=' ')
else:
# print(len(str(j)) * ' ', end=' ')
# condition_is_true if condition else condition_is_false
print(len(str(j)) * ' ' if j > i else j, end=' ')
print()
#
triangle_print(12)
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
# print?
# print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
python 中一切皆对象,对象都是引用类型,可以理解为一个地址指针指向该对象
2、列表
# list?
# list(iterable=(), /)
# 变量是一个标识符,指向一个对象,而这个对象被创建在内存‘堆’中;
x = [1]
a = [x] * 3 # a = [[1], [1], [1]]
print(1, a)
a[1][0] = 500
print(2, a)
1 [[1], [1], [1]]
2 [[500], [500], [500]]
a = [1]
b = range(5)
x = [a, b]
x.clear() # 清空列表内的指向地址
print(x) # []
a = [1, [2, 3, 4], 5]
b = a.copy() # 浅拷贝
a[1][1] = 200
print(1, a == b, a ,b)
1 True [1, [2, 200, 4], 5] [1, [2, 200, 4], 5]
import copy
a = [1, [2, 3, 4], 5]
b = copy.deepcopy(a) # 深拷贝
a[1][1] = 200
print(2, a == b, a ,b)
2 False [1, [2, 200, 4], 5] [1, [2, 3, 4], 5]
import random
# random.randrange?
# Choose a random item from range(start, stop[, step]).
3、元组
# tuple?
# tuple(iterable=(), /)
a = ([3],) * 3
print(1, a)
a[0][0] = 400 # 元组的元素是列表
print(2, a)
a[1].append(4)
print(3, a)
1 ([3], [3], [3])
2 ([400], [400], [400])
3 ([400, 4], [400, 4], [400, 4])
4、字符串
s = 'mageedu.edu'
print(s.index('edu')) # S.index(sub[, start[, end]]) -> int
# s.index?
print(s.count('edu'))
4
2
x1 = ",".join(map(str, range(1, 6)))
print(x1)
x2 = map(str, range(1, 6))
print(x2)
y1 = '.'.join(['ab', 'pq', 'rs'])
print(y1)
1,2,3,4,5
<map object at 0x000001F81787B3A0>
ab.pq.rs
s = ','.join('abcd')
print(s)
print(s.split(',', 2)) # str.split(self, /, sep=None, maxsplit=-1)
print(s.partition(',')) # str.partition(self, sep, /)
a,b,c,d
['a', 'b', 'c,d']
('a', ',', 'b,c,d')
# str.replace(self, old, new, count=-1, /)
d = "www.magedu.com".replace('w', 'a', 20)
print(d)
# str.strip(self, chars=None, /)
'\r\n\t a\nb\r\nc\rd\te \n \t f\f\t'.strip()
aaa.magedu.com
'a\nb\r\nc\rd\te \n \t f'
s1 = "My name is %s, I am %d" % ("Tom", 20) # C 风格
s2 = "My name is %(name)s, I am %(age)d" % {'age':200, 'name':'Jerry'}
print(s1)
print(s2)
My name is Tom, I am 20
My name is Jerry, I am 200
import datetime
d1 = datetime.datetime.now()
print(d1)
2022-07-18 00:38:00.554713
"{:%Y/%m/%d %H:%M:%S}".format(d1)
'2022/07/18 00:38:00'
"{0:#b} {0:#x} {0:#X} {0:#o}".format(31)
'0b11111 0x1f 0X1F 0o37'
'''
00000000 0 null '\x00'
00000000 int 0
00001001 '\x09' '\t'
00001010 '\x0a' '\n'
13 0x0D '\x0d' '\r'
65 0x41 '\x41' 'A'
97 0x61 '\x61' 'a'
48~57 '\x30'~'\x39' '0'~'9'
'''
"\n00000000 0 null '\x00'\n00000000 int 0\n00001001 '\t' '\t'\n00001010 '\n' '\n'\n13 0x0D '\r' '\r'\n65 0x41 'A' 'A'\n97 0x61 'a' 'a'\n48~57 '0'~'9' '0'~'9'\n"
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[::2]) # 切片不改变类型 sequence[start:stop:step] step控制方向,前包后不包
print(x[2:8:3])
print(x[-10:8:2])
print('0123456789'[-4:8])
print(b'0123456789'[-4:8])
print(bytearray(b'0123456789'[-10:5]))
[0, 2, 4, 6, 8]
[2, 5]
[0, 2, 4, 6]
67
b'67'
bytearray(b'01234')
print(id([1, 2, 3, 5, 4]))
print(id([1, 2, 3]))
# 同一时间点,同时存在的对象,如果id内存地址一样,一定是同一个对象
2165058235136
2165058266880
#str.format?
print("{server} {1}:{0}".format(8080, '127.0.0.1', server='web server info: '))
print("{:20.3f}".format(0.2745))
print("{}*{}={:4}".format(5, 6, 5*6))
print("{1}*{0}={2:3}".format(5, 6, 5*6)) # 2对应5*6
print("{:^{}}".format(4, 7))
web server info: 127.0.0.1:8080
0.275
5*6= 30
6*5= 30
4
5、哈希表
1. set、dict使用hash表实现,内部使用hash值作为key,时间复杂度为O(1),查询时间和数据规模无关,不会随着数据规模增大而搜索性能下降;
5.1 不可变类型,都是可hash类型
1. 线性数据结构,搜索元素的时间复杂度是O(n),即随着数据规模增加耗时增大;
2. 数值型:int,float,complex
3. 布尔型:True,Flase
4. 字符串:string,bytes
5. 元组:tuple
6. None
5.2 解构
a, *r= b'abc'
print("a={}".format(a))
print(r) # 返回列表 *rest, 剩余
x = [*(1, 2)]
print (x, len(x)) # 解构
y = [range(5)]
print(y, len(y))
y1 = [*range(5)] # 解构
print(y1, len(y1))
y2 = [_, [*_, c], _] = [1, [2, 3, 4], 5]
print(y2)
a=97
[98, 99]
[1, 2] 2
[range(0, 5)] 1
[0, 1, 2, 3, 4] 5
[1, [2, 3, 4], 5]
path = r'c:\windwos\nt\drivers\etc'
dirname, _, basename = path.rpartition('\\')
dirname
'c:\\windwos\\nt\\drivers'
basename
'etc'
6、集合
# 集合set 元素不重复, 无序
# set元素必须是可hash的,不可变类型称为可哈希类型
# set(self, /, *args, **kwargs)
set(range(5)), {1, 2, 'ab'}, set((1, 2, 3)), {*range(5), *[1, 2, 3]}
({0, 1, 2, 3, 4}, {1, 2, 'ab'}, {1, 2, 3}, {0, 1, 2, 3, 4})
x = {1, 'abc'}
x.update(range(3), 'abc')
print(x)
x.add('abc')
print(x)
x.update('xyz', ['tyu'])
print(x)
{0, 1, 2, 'c', 'abc', 'a', 'b'}
{0, 1, 2, 'c', 'abc', 'a', 'b'}
{0, 1, 2, 'c', 'z', 'x', 'tyu', 'abc', 'a', 'b', 'y'}
x.remove('a')
print(x)
# x.clear()
{0, 1, 2, 'c', 'z', 'x', 'tyu', 'abc', 'b', 'y'}
# 线性表 in O(n), 哈希表 O(1)
# 线性表遍历、哈希表遍历 O(n)
hash1 = hash('b') # 0x62 01100010 98 128 64 32 16 8 4 2 1
hash2 = hash('c') # 0x63 01100011 99
print("hash1: %s" % hash1)
print("hash2: {}".format(hash2))
hash1: 981093712798055480
hash2: -4706994542336696731
7、字典
# dict(self, /, *args, **kwargs)
# 字典是可变的、无序的、key(hash)不重复的键值对集合
# dict.fromkeys(iterable, value=None, /)
dict.fromkeys(range(5), 0)
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
dict({'a':1, 'b':100, 1:'abc'}, a=2, c=300)
{'a': 2, 'b': 100, 1: 'abc', 'c': 300}
dict([('a', 1), [1, 100]], a=2)
{'a': 2, 1: 100}
d1 = dict.fromkeys('abcde', [1])
print(d1)
{'a': [1], 'b': [1], 'c': [1], 'd': [1], 'e': [1]}
d1['d'] = 5
print(d1)
d1['b'][0] = '2'
print(d1)
{'a': [1], 'b': [1], 'c': [1], 'd': 5, 'e': [1]}
{'a': ['2'], 'b': ['2'], 'c': ['2'], 'd': 5, 'e': ['2']}
d1 = {'a':1, 'b':'abc', 'c':False, 'd':[1]}
d1['c'], 'd' in d1, 'c' in d1
(False, True, True)
d1.get('b')
'abc'
x = [1]
a = x
b = x
print(id(a), id(b))
c = [1]
d = [1]
print(id(c), id(d))
2130251129024 2130251129024
2130228614592 2130230601600
import sys
sys.getrefcount(d1['d'])
2
{i:j for i in 'abcd' for j in range(3)}
{'a': 2, 'b': 2, 'c': 2, 'd': 2}
{i:j for i in 'abcd' for j in range(3, 0, -1)}
{'a': 1, 'b': 1, 'c': 1, 'd': 1}
列表是可迭代对象,生成器也是可迭代对象
生成器也是迭代器一种,但列表不是迭代器
迭代器的特点:
> 一次性迭代,指针不会回头;
> 类似range(range不是迭代器),是惰性的,使用next挤一下;
> for 循环可以迭代,但是如果已经到头,for相当于迭代空容器,但是next不能迭代,如果使用next会抛出StopInteration异常;
# 有一个列表lst=[1, 4, 9, 16, 2, 5, 10, 15],生成新列表,要求是lst相邻2项之和
lst=[1, 4, 9, 16, 2, 5, 10, 15]
newLst = []
for i in range(len(lst) -1):
# print(i, i+1)
newLst.append(lst[i] + lst[i+1])
print(newLst)
print([lst[i] + lst[i+1] for i in range(len(lst) - 1)])
[5, 13, 25, 18, 7, 15, 25]
[5, 13, 25, 18, 7, 15, 25]
# 随机生成100个产品ID,ID格式 000005.xcbaaduixy
import string
import random
print(string.ascii_lowercase)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = "".join(chr(i) for i in range(0x61, 0x61+26))
for i in range(1, 6):
id = "{:0>6}.{}".format(i, "".join(random.choices(alphabet, k=10)))
print(id)
abcdefghijklmnopqrstuvwxyz
000001.taytosudjj
000002.iqfxplvkpv
000003.ptjgkyabhe
000004.xrmmibhjpt
000005.hzmiapmusb
# random.choices?
# random.choices(population, weights=None, *, cum_weights=None, k=1)
本文来自博客园,作者:anyu967,转载请注明原文链接:https://www.cnblogs.com/anyu967/articles/17501921.html
浙公网安备 33010602011771号