AllenObserver

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

  

#  操作列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:  # 遍历整个列表
    print(magician)
print('\n')

for magician in magicians:
    print(magician.title() + ", that was a great trick!")
print('\n')

for magician in magicians:
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great magic show!")

#  创建数值列表
for value in range(1, 5):  # 使用函数range()
    print(value)  # 使用range()时,如果输出不符合预期,请尝试将指定的值加1或减1。

numbers = list(range(1, 6))  # 使用range()创建数字列表
print(numbers)

even_numbers = list(range(2, 11, 2))  # 指定步长
print(even_numbers)

squares = []  # 创建了一个空列表
for value in range(1, 11):
    squares.append(value ** 2)
print(squares)

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

# 列表解析
squares = [value ** 2 for value in range(1, 11)]
print(squares)

# 练习
one_twenty = [number for number in range(1, 1000001)]
print(min(one_twenty))
print(max(one_twenty))
print(sum(one_twenty))

# 处理列表的部分元素——Python称之为切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])  # 要创建切片,可指定要使用的第一个元素和最后一个元素的索引, 且不包含最后一个元素。
print(players[1:4])
print(players[:4])  # 如果你没有指定第一个索引,Python将自动从列表开头开始。
print(players[2:])  # 要让切片终止于列表末尾。
print(players[-3:])  # 从特定位置到列表末尾的所有元素。最后三个。

# 遍历切片
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

# 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]  # 创建了这个列表的副本。如friend_foods = my_foods则只是将my_foods赋值给friend_foods
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

# 元组:Python将不能修改的值称为不可变的 , 而不可变的列表被称为元组
# 定义元组
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# dimensions[0] = 250  不能给元组的元素赋值
# 遍历元组中的所有值
for dimension in dimensions:
    print(dimension)
# 修改元组变量
# 虽然不能修改元组的元素,但可以给存储元组的变量赋值。
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)

 

posted on 2017-03-24 16:23  AllenObserver  阅读(91)  评论(0编辑  收藏  举报