python的列表操作教学

#遍历整个列表
magicians=['alice','david','carolina']
for magician in magicians:
    print(magician)# 不要忘记冒号,记住要缩减

#在for循环中执行更多的操作
magicians=['alice','david','carolina']
for magician in magicians:
    print(magician.title()+", that was a great trick")
    print("I can't wait to see you next trick, "+magician.title() +".\n")# 多行语句要同时缩进

#使用函数range()
for value in range(1,5):
    print(value)# 从1到4总共四个数

#使用range()创建数字列表
numbers=list(range(1,6))
print(numbers)
numbers=list(range(2,11,2))# 从2开始依次加2但最后一定要小于11
print(numbers)
numbers=list(range(2,11,1))
print(numbers)
numbers=list(range(2,11,3))# 从2开始依次加3但最后一定要小于11
print(numbers)

#列表解析
squares=[]
for value in range(1,11):
    square=value**2# 代表乘方运算
    squares.append(square)
print(squares)

squares=[value**2 for value in range(1,11)]
print(squares)

#对数字列表执行简单的统计运算
digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))

#切片
players=['charles','martina','michael','florence','eli']
print(players[0:3])# 从第一个到第三个输出
print(players[2:4])# 从第三个到第四个输出
print(players[:4])# 输出前四个
print(players[2:])# 从第三个开始输出
print(players[-3:])# 从从后往前数第三个开始输出

#遍历切片
players=['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

#复制列表
players=['charles','martina','michael','florence','eli']
players_1=players[:]

#定义元组
dimensions=(200,50)# 不能修改的列表叫做元组,用圆括号表示
print(dimensions[0])

#遍历元组中所有的值
dimensions=(200,50)
for dimension in dimensions:
    print(dimension)
    



python的列表操作教学python的列表操作教学 Corey770 发布了9 篇原创文章 · 获赞 0 · 访问量 172 私信 关注
上一篇:怎么样对数据库索引维护那?


下一篇:C#学习笔记——Queue队列