Python - 4 - 操作列表

4.1 遍历整个列表
使用 for 循环

#!/usr/bin/python
# -*-  coding: latin-1 -*-
import os, sys

#4.1 遍历整个列表,使用for循环
magicians = ['alice','david','carolina']
for magician in magicians:
	print(magician)

output:
alice
david
carolina


#4.1.1  对列表中的每个元素,都将执行循环指定的步骤
#4.1.2  在for循环中执行更多操作
#对每位魔术师输出表演很精彩
magicians = ['alice','david','carolina']
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")

output:	
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.


#4.1.3  在 for 循环结束后执行一些操作
magicians = ['alice','david','carolina']
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, eceryone, That was a great magic shou!")

output:
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, eceryone, That was a great magic shou!



#4.1	避免缩进错误
#4.2.1	忘记缩进   IdentationError: expected an indented block
#4.2.2	忘记缩进额外的代码行
magicians = ['alice','david','carolina']
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, eceryone, That was a great magic shou!")

output:
Alice , that was a great trick!
David , that was a great trick!
Carolina , that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, eceryone, That was a great magic shou!



#4.2.3	不必要的缩进  IndentationError: unexpected indent
#message = "Hello Python world!"
#	print(message)


#4.2.4	循环后不必要的缩进,逻辑错误,语法可能无误
magicians = ['alice','david','carolina']
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, eceryone, That was a great magic shou!")

output:
Alice , that was a great trick!
I can't wait to see your next trick, Alice.

Thank you, eceryone, That was a great magic shou!
David , that was a great trick!
I can't wait to see your next trick, David.

Thank you, eceryone, That was a great magic shou!
Carolina , that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, eceryone, That was a great magic shou!



#4.2.5	遗漏了冒号 SyntaxError: invalid syntax
#magicians = ['alice','david','carolina']
#for magician in magicians
#	print(magician)



#Quiz
#4-1	披萨
#4-1.1
pizzas = ['banana','apple','orange']
for pizza in pizzas:
	print(pizza)

output:
banana
apple
orange

#4-1.2	
for pizza in pizzas:
	print("I like "+pizza+" pizza.")

output:
I like banana pizza.
I like apple pizza.
I like orange pizza.

#4-1.3
pizzas = ['banana','apple','orange']
for pizza in pizzas:
	print("I like "+pizza+" pizza.")

print("Apple,Banana,Orange pizza are all my favorite, I really love pizza!")

output:
I like banana pizza.
I like apple pizza.
I like orange pizza.
Apple,Banana,Orange pizza are all my favorite, I really love pizza!

#4-2	动物
#4-2.1
animals = ['cat','dog','rabbit']
for animal in animals:
	print(animal)

output:
cat
dog
rabbit

#4-2.2
animals = ['cat','dog','rabbit']
for animal in animals:
	print(animal)
	print("A "+animal+" would make a great pet.")

output:
cat
A cat would make a great pet.
dog
A dog would make a great pet.
rabbit
A rabbit would make a great pet.

#4-2.3
animals = ['cat','dog','rabbit']
for animal in animals:
	print(animal)
	print("A "+animal+" would make a great pet.")
print("Any of these animals would make a good pet!")

output:
cat
A cat would make a great pet.
dog
A dog would make a great pet.
rabbit
A rabbit would make a great pet.
Any of these animals would make a good pet!

#	创建数值列表
#4.3.1	使用函数range(),"差一行",从指定的第一个值开始,到达指定的第二个值后停止。
#要打印数字1~5,需要使用range(1,6),使用range时若输出不符合预期尝试将指定值加或减1
for value in range(1,5):
	print(value)

##output:
#1
#2
#3
#4


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

##output:
#1
#2
#3
#4
#5


#	使用range()创建数字列表
#	函数list()将range()的结果直接转换为列表
numbers = list(range(1,6))
print(numbers)

##output
#[1, 2, 3, 4, 5]


#	输出1~10内的偶数
even_numbers = list(range(2,11,2))
print(even_numbers)

##output
#[2, 4, 6, 8, 10]


#	输出1~10内的奇数
odd_numbers = list(range(1,10,2))
print(odd_numbers)

##outpt
#[1, 3, 5, 7, 9]


#	创建1~10平方的列表
squares = []
for value in range(1,11):
	square = value**2
	squares.append(square)
	#squares.append(value**2)
print(squares)

##output
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]



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

##output
#1
#7
#28



#4.3.4	列表解析:将for循环和创建新元素的代码合并成一行,并自动附加新元素
#要使用这种语法,首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,
#并定义一个表达式,用于生成你要存储到列表中的值,在该实例中,表达式为value**2,
#它计算平方值。编写for循环,用于给表达式提供值,再加上右方括号。
squares = [value**2 for value in range(1,11)]
print(squares)

##output
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]





#Quiz 4-3_4-9
#for 循环遍历[1,20]并print输出
#TypeError: 'tuple' object is not callable
#range = (1,21)
#for value in range(1,21):
#	print(value)

#4-3 use a for loop to print the numbers from 1 to 20,inclusive
numbers = list(range(1,21))
for number in numbers:
	print(number)

##output
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#11
#12
#13
#14
#15
#16
#17
#18
#19
#20

#4-4 use a for loop to print the numbers from 1 to 1000000,
#numbers = list(range(1,1000001))
#for number in numbers:
#	print(number)

#4-5	make a list of numbers from one to one million, then use min(),
#max() to make sure your list starts at one and ends at one million. 
#Also use the sum() function to see how quickly Python can add a million 
#numbers
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))

##output
#1
#1000000
#500000500000


#4-6	use a for loop to print odd numbers between 1 and 20
odd_numbers = list(range(1,21,2))
for odd_number in odd_numbers:
	print(odd_number)

##output
#1
#3
#5
#7
#9
#11
#13
#15
#17
#19

#4-7	use a for loop to print multiples of 3 from 3 to 30
mutiples = list(range(3,31,3))
for multiple in mutiples:
	print(multiple)

##output
#3
#6
#9
#12
#15
#18
#21
#24
#27
#30


#4-8	use a for loop to print the value of cube of each integer from
#       1 through 10
numbers = list(range(1,11))
for number in numbers:
	cube = number**3
	print(cube)

##output:
#1
#8
#27
#64
#125
#216
#343
#512
#729
#1000

	
#	创建空列表cubes,cube元素append添加,for loop print cube
cubes = []
for number in range(1,11):
	cube = number**3
	cubes.append(cube)
print(cubes)
for cube in cubes:
	print(cube)

##output:
##[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
#1
#8
#27
#64
#125
#216
#343
#512
#729
#1000


#	列表解析  SyntaxError: keyword can't be an expression 
#print(cube in cubes = [number**3 for number in range(1,11)])

#4-9	列表解析	
cubes = [number**3 for number in range(1,11)]
print(cubes)
for cube in cubes:
	print(cube)

##output:
##[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
#1
#8
#27
#64
#125
#216
#343
#512
#729
#1000


#4.4	使用列表的一部分
#4.4.1	切片:处理列表中的部分元素,要创建切片,可指定要使用的第一个元素和最后一个元素
#的索引。在到达指定的第二个索引前面的元素后停止。若未指定第一个索引,python将自动从列表
#开头开始;若未指定终止索引,则至列表末尾。负数索引返回离列表末尾相应距离的元素
players = ['charles','martina','michael','florence','eli']
#输出前三位 TypeError: list indices must be integers or slices, not tuple
#print(players[0,3])
print(players[0:3])

##output:
##['charles', 'martina', 'michael']

#输出第二至第四位
print(players[1:4])

##output
##['martina', 'michael', 'florence']

#无起始索引
print(players[:4])

##output:
##['charles', 'martina', 'michael', 'florence']

#无终止索引
print(players[2:])

##output
##['michael', 'florence', 'eli']

#负数索引,返回离列表末尾相应距离的元素
print(players[-3:])

##output
##['michael', 'florence', 'eli']



#4.4.2 遍历切片,在for循环中使用切片
players = ['charles','martina','michael','florence','eli']
for player in players[0:3]:
	print(player)
	
##output:
#charles
#martina
#michael


#4.4.3 复制列表
#创建包含整个列表的切片
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
#friend_foods = my_foods
print("my favorite foods are ")
print(my_foods) 
print("my friend's favorite foods are ")
print(friend_foods)

##output:
#my favorite foods are
#['pizza', 'falafel', 'carrot cake']
#my friend's favorite foods are
#['pizza', 'falafel', 'carrot cake']

#每个列表添加一种食品
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("my favorite foods are ")
print(my_foods) 
print("my friend's favorite foods are ")
print(friend_foods)

##output
#my favorite foods are
#['pizza', 'falafel', 'carrot cake', 'cannoli']
#my friend's favorite foods are
#['pizza', 'falafel', 'carrot cake', 'ice cream']

#简单地将my_foods 赋值给 friend_foods,让Python将新变量friend_foods关联到包含
#在my_foods中的列表,因此这两个变量都指向同一个列表
my_foods = ['pizza','falafel','carrot cake']
#friend_foods = my_foods[:]
friend_foods = my_foods
print("my favorite foods are ")
print(my_foods) 
print("my 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("my friend's favorite foods are ")
print(friend_foods)

##output:
#my favorite foods are
#['pizza', 'falafel', 'carrot cake']
#my friend's favorite foods are
#['pizza', 'falafel', 'carrot cake']
#my favorite foods are
#['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
#my friend's favorite foods are
#['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']


#Quiz
#4-10
foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream','chicken','duck','fish']
print("The first three items in this list here are: ")
print(foods[0:3])
print("Three items from the middle of the list are: ")
print(foods[2:5])
print("The last three items in the list are: ")
print(foods[-3:])

##output
#The first three items in this list here are:
#['pizza', 'falafel', 'carrot cake']
#Three items from the middle of the list are:
#['carrot cake', 'cannoli', 'ice cream']
#The last three items in the list are:
#['chicken', 'duck', 'fish']

#4-11
favorite_pizzas = ['pepperoni', 'hawaiian', 'veggie']
friend_pizzas = favorite_pizzas[:]
favorite_pizzas.append('banana')
friend_pizzas.append('apples')
print("my favorite pizzas are: ")
for pizza in favorite_pizzas:
	print("-"+pizza)
print("\nmy friends' favorite pizzas are: ")
for pizza in friend_pizzas:
	print("-"+pizza)


##output
#my favorite pizzas are:
#-pepperoni
#-hawaiian
#-veggie
#-banana

#my friends' favorite pizzas are:
#-pepperoni
#-hawaiian
#-veggie
#-apples




#4.5	元组:不能修改的值称为不可变的,而不可变的列表被称为元组
#4.5.1 定义元组:()而非[]   可使用索引来访问其元素
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

##output
#200
#50

#修改元组元素值 TypeError: 'tuple' object does not support item assignment
#dimensions[0] = "77"

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

##output:
#200
#50

#4.5.3 修改元组变量
#虽元组元素不可修改,但可对存储元组的变量赋值
dimensions = (200,50)
print("Original dimensions: ")
for dimension in dimensions:
	print(dimension)
dimensions = (400,100)
print("\nModified dimensions: ")
for dimension in dimensions:
	print(dimension)

##output
#Original dimensions:
#200
#50

#Modified dimensions:
#400
#100


#Quiz
#4-13 Buffet
#five simple food stored in a tuple
foods = ('apple','banana','orange','fish','chicken')
print("The original foods list is: ")
for food in foods:
	print("-"+food)
#修改元素  TypeError: 'tuple' object does not support item assignment
#foods[0] = "TV set"
#重新定义元组变量,替换其中两种食物
print("\nThe updated foods list is: ")
foods = ('apple','banana','orange','peach','lemon')
for food in foods:
	print("-"+food)

##output
#The original foods list is:
#-apple
#-banana
#-orange
#-fish
#-chicken

#The updated foods list is:
#-apple
#-banana
#-orange
#-peach
#-lemon



#4.6   设置代码格式

#4.6.1 格式设置指南
#Python改进提案(Python Enhancement Proposal,PEP)。PEP8是最古老的PEP之一,提供了代码格式指南。代码易于阅读较易于编写更重要。

#4.6.2 缩进
#PEP8 建议每级缩进都使用四个空格。在字处理文档中,大家常使用制表符而#非空格来缩进。混合使用制表符和空格会使Python解释器感到迷惑。每款文##本编辑器都提供了一种设置,可将输入的制表符转换成指定数量的空格,在#编写代码时应该使用制表符键,但一定要对编辑器进行设置,使其在文档中插#入空格而不是制表符。若混合使用了制表符和空格,可将文件中所有的制表符#转换成空格。

#4.6.3 行长
#建议每行不超过80字符;注释行长都不超过72字符;

#4.6.4 空行
#空行可将程序的不同部分分开,可使用空行来组组织文件。Python解释器根##据水平缩进情况来解读代码,而不关心垂直间距。

#4.6.5 其他格式设置指南
#参见PEP8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值