Python学习之路,点击有全套Python笔记
语法:
for 临时变量 in 序列:
重复执⾏的代码1
重复执⾏的代码2
name_list = ['jack', 'tom', 'tony', 'rose']
for i in name_list:
print(i)
# jack
# tom
# tony
# rose
# 先来了解zip
# 在Python2中,是这样的
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
print(zipped) #[(1, 4), (2, 5), (3, 6)]
# 但是在Python3中,需要用for来输出
a = [1, 2, 3]
b = [4, 5, 6]
for i in zip(a, b):
print(i)
# (1, 4)
# (2, 5)
# (3, 6)
# 再来了解一下format,一种格式化输出
print("{0}, {1}, {0}, {1}".format('hello', 'world'))
# hello, world, hello, world
# 最后将他们组合起来
names = ("tom", "jack", "rose", "jerry")
ages = (18, 19, 20, 21)
jobs = ('老师', '程序猿', '公务员', '无业')
for name, age, job in zip(names, ages, jobs):
print("{0},{1},{2}".format(name, age, job))
# tom, 18, 老师
# jack, 19, 程序猿
# rose, 20, 公务员
# jerry, 21, 无业
进阶版还有若干,后面会与if等出合集
# 先了解range
# range是一个轻松生成一系列数字的函数
# range(start, stop, step) 含左不含右
numebers = list(range(10))
print(numebers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 建立普通的推导式
value = [values**2 for values in range(1, 12)]
print(value) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
# 三角形
for i in range(5):
print("*" * (i+1))
'''
*
**
***
****
*****
'''
# 实心矩形
for i in range(5):
print("*" * 5)
‘’‘
*****
*****
*****
*****
*****
’‘’
# 金字塔
for i in range(5):
print(" " * (4-i), end="")
print("* " * (i+1))
'''
*
* *
* * *
* * * *
* * * * *
'''
names = ("tom", "jack", "rose", "jerry")
for i in names[-3:]:
print(i)
# jack
# rose
# jerry
for的简单用法就这些,其他的会在后面出合集,将这些东西放在一起用