Python数据基础类型-新建列表

1,遍历列表

  遍历列表的所有元素,对每个元素执行相同的操作。可使用for循环

magicians = ['alice','david','carolina']
for magician in magicians:
  print(magician)
运行结果
alice david carolina
magicians = ['alice','david','carolina']
for magician in magicians:
    #print(magician)
    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!")
运行结果
Alice, that was a great trick! I can
't wait to see your next trick, Alice. David, that was a great trick! I can't wait to see your next trick, David. Carolina, that was a great trick! I can't wait to see your next trick, Carolina. Thank you, everyone. That was a great magic show!

 2,创建数字列表

 一,列表非常适合用于存储数字集合,函数range()能够轻松生成一系列的数字。  

for value in range(1,5):
    print(value)
运行结果
1
2
3
4

  二,使用range()创建数字列表。可使用函数list()将range()的结果直接转换成列表。还可指定步长。

numbers = list(range(1,6))
print(numbers)
运行结果
[1, 2, 3, 4, 5]

   三、列表解析

  列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。

  语法:描述性的列表名 = 【表达式(用于存储到列表中的值)  for循环】

squares = []
for value in range(1,11):
    squares.append(value**2)
print(squares)
View Code
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
result
squares = [value**2 for value in range(1,11)]
print(squares)
View Code
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
result

  四、切片

  1,处理列表的部分元素-称之为切片 

players = ['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
print(players[:-3])
View Code
['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'martina']
result

  2,遍历切片

players = ['charles','martina','michael','florence','eli']
print("\nHere are the first three players on my team:")
for player in players[:3]:
    print(player.title())
View Code
运行结果:
Here are the first three players on my team:
Charles
Martina
Michael
result

  3,复制列表

3,元组

  Python的元组与列表类似,不同之处在于元组的元素不能修改。

  元组使用小括号,列表使用方括号。

  元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

  如下实例:

  

dimensions = (200,50)
#dimensions[0] = 250 修改无组值报错
print(dimensions[0])
print(dimensions[1])

#遍历元组中的所有值,for循环
for dimension in dimensions:
    print(dimension)
@修改元组变量
dimensions = (250,50)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)
View Code
运行结果:
200
50
200
50

Modified dimensions:
250
50
result

 

你可能感兴趣的:(Python数据基础类型-新建列表)