您的位置:首页 > 编程语言 > Python开发

Python学习笔记_4_列表(2)

2018-03-06 23:30 162 查看

关于列表的学习记录(2)

1. for循环

list_of_names=['david','alice','nancy','molly','jack']
for name in list_of_names:
print(name.title()+", I can't wait to see you!")
print("I want see your next performance, "+name.upper()+".\n")
print("Thank you for all! ")


David, I can’t wait to see you!

I want see your next performance, DAVID.

Alice, I can’t wait to see you!

I want see your next performance, ALICE.

Nancy, I can’t wait to see you!

I want see your next performance, NANCY.

Molly, I can’t wait to see you!

I want see your next performance, MOLLY.

Jack, I can’t wait to see you!

I want see your next performance, JACK.

Thank you for all!

注意缩进,正确使用缩进

for语句中注意冒号:的使用!

2. 使用range创造数值列表

for value in range(1,7):
print(value)

numbers=list(range(1,6))
print(numbers)

even_numbers=list(range(1,12,2))
print(even_numbers)


1

2

3

4

5

6

[1, 2, 3, 4, 5]

[1, 3, 5, 7, 9, 11]

同时使用range()和list()函数来实现列表的创建。

squares=[]

for num in range(1,10,2):

square=num**2

squares.append(square)

print(squares)

squares=[]
for num in range(1,10,2):
squares.append(num**2)
print(squares)

digits=[1,6,3,7,99,44,66,34,21]
print(min(digits))
print(max(digits))
print(sum(digits))


[1, 9, 25, 49, 81]

[1, 9, 25, 49, 81]

1

99

281

列表解析

mutu=[mu**2 for mu in range(1,5)]
print(mutu)


[1, 4, 9, 16]

3. 切片——列表的一部分

players=['c','b','d','m','o']
print(players[1:4])
print(players[4:])
print(players[-3:])

print("Here are three players: ")
for player in players[1:4]:
print(player.title())

my_food=['pizza','noodles','cake']
friend_food=my_food[:]
my_food.append('ice')
friend_food.append('cannoli')
print(my_food)
print(friend_food)

another_food=my_food
my_food.append('cream')
another_food.append('carrot')
print(my_food)
print(another_food)


[‘b’, ‘d’, ‘m’]

[‘o’]

[‘d’, ‘m’, ‘o’]

Here are three players:

B

D

M

[‘pizza’, ‘noodles’, ‘cake’, ‘ice’]

[‘pizza’, ‘noodles’, ‘cake’, ‘cannoli’]

[‘pizza’, ‘noodles’, ‘cake’, ‘ice’, ‘cream’, ‘carrot’]

[‘pizza’, ‘noodles’, ‘cake’, ‘ice’, ‘cream’, ‘carrot’]

4. 元组

dimentions=(100,200)
print(dimentions[0])

print("\nOriginal dimentions: ")
for dimention in dimentions:
print(dimention)

dimentions=(400,100)
print("\nModified dimentions")
for dimention in dimentions:
print(dimention)


100

Original dimentions:

100

200

Modified dimentions

400

100

元组的值不可修改,除非重新命名.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: