重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
x = 'spam'
while x:
print(x, end=' ')
x = x[1:] # spam pam am m
站在用户的角度思考问题,与客户深入沟通,找到松桃网站设计与松桃网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计、做网站、企业官网、英文网站、手机端网站、网站推广、域名注册、网络空间、企业邮箱。业务覆盖松桃地区。
def func():
pass
def func():
...
x = 10
while x:
x = x-1
if x % 2 ==0:continue
print(x, end=' ') # 9 7 5 3 1
#判断是不是质数
#x = y //2
#while x > 1:
#else:
for i in 'spam':
print(i, end='') # spam
sum = 0
for i in [1, 2, 3]:
sum += i
print(sum) # 6
sum = 1
for i in [1, 2, 3, 4]:sum *= i
print(sum) # 24
#for循环中的元组赋值和解包
for (i, j) in ((1, 2),(3, 4)): # 1 2
print(i, j) # 3 4
d = {'a':1,'b':2,'c':3} # 'a' 1
for i in d: # 'b' 2
print(i, d[i]) # 'c' 3
for (i, j) in d.items(): # 'a' 1
print(i, j) # 'b' 2
t = [(1, 2), (3, 4), (5, 6)]
for both in t: # 1, 2
a, b = both # 3, 4
print(a, b) # 5, 6
for ((a, b), c) in [((1, 2),3), ((4, 5), 6)]: # 1 2 3
print(a, b, c) # 4 5 6
for ((a, b), c) in [((1, 2),3), ('xy', 6)]: # 1 2 3
print(a, b, c) # x y 6
a, *b, c = (1, 2, 3, 4)
print(a, b, c) # 1 [2, 3] 4
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
print(a, b, c)
items = ['aaa', 111, (4, 5), 2.01]
tests = [(4, 5), 3.14]
for key in tests:
for item in items:
if item == key:
print(key, 'was found')
break
else:
print(key, 'not found')
for key in tests:
if key in items:
print(key, 'was found')
else:
print(key, 'not found')
#编写循环技巧
#灵活使用range, range在py3 中是迭代器
print(range(5)) # range(0, 5)
print(list(range(5))) # [0, 1, 2, 3, 4]
l = [1, 2, 3, 4, 5]
for x in l:
x += 1
print(l) # [1, 2, 3, 4, 5]
#每次经过循环时, x会引用从列表中取出来的下一个整数。
#也就是2, 但是没更新1所来自的那个列表
l = [1, 2, 3, 4, 5]
for i in range(len(l)):
l[i] += 1
print(l) # [2, 3, 4, 5, 6]
print([i+1 for i in [1, 2, 3, 4, 5]])
#并行遍历,zip 和 map
#元素配成对
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
print(zip(l1, l2)) #
print(list(zip(l1, l2))) # [(1, 5), (2, 6), (3, 7), (4, 8)]
for (x, y) in zip(l1, l2):
print(x, y, '-->', x+y)
s1 = 'abc'
s2 = 'xyz123'
#print(list(map(None, s1, s2)))
print(list(map(ord, 'spam'))) # [115, 112, 97, 109]
#用zip构造字典
k = ['spam', 'eggs', 'toast']
v = [1, 3, 5]
print(list(zip(k, v)))
d = {}
for i, j in zip(k, v):
d[i] = j
print(d)
k = ['spam', 'eggs', 'toast']
v = [1, 3, 5]
d = dict(zip(k, v))
print(d)
{'spam': 1, 'eggs': 3, 'toast': 5}
s = 'spam'
for i, j in enumerate(s):
print(i,'-->',j)
e = enumerate('spam')
print(e)
#这个对象有个next方法,可以在每次迭代的时候返回一个元组,
#可以在for中循环通过元组赋值将运算解包
print(next(e))
print(next(e))
print(next(e))