Day 2 of Learning Python

Day 2 of Learning Python

在这里插入图片描述

Chapter 4 操作列表

4.1遍历整个列表

可以使用for循环来边里列表的所有元素。注意书写格式:冒号与缩进。

magicians=['alice','david','carolina']
for magician in magicians:
    print(magician.title()+', that was a great trick!')

运行结果为

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!

4.3 创建数值列表

函数range()可以生成一系列的数字。

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

运行结果为
1
2
3
4

这是编程语言差一行为的结果。range() 让Python从指定的第一个值开始数,在到达你指定的第二个值时结束,但不包含第二个值。
函数list()将range()的结果直接转换为列表。使用函数range()时,还可指定步长。

even_numbers = list(range(2,11,2))
print(even_numbers)

运行结果
[2, 4, 6, 8, 10]

创建一个列表,包含1~10的平方。

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

结果为[1, 4, 9, 16, 25, 36, 49, 64, 81]
几个专门处理数字列表的函数,最小值min, 最大值max, 总和sum.

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)

0

max(digits)

9

sum(digits)

45

列表解析

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

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

运行结果与平方数列表相同。
要使用这种语法,首先指定一个描述性列表明,如squares;然后指定一个左方括号并定义一个表达式,用于生成你要存储到列表中的值,如value* *2。 接下来,编写一个for循环,用于给表达式提供值,再加上右方括号,如for value in range(1,11),它将值1~10提供给表达式value**2。注意,这里的for语句末尾没有冒号。
练习题4-3~4-9

for value in range(1,21):      #数到20
    print(value)

numbers=list(range(1,1000001))    #一百万

print(min(numbers))
print(max(numbers))
print(sum(numbers))

even_numbers=list(range(1,21,2)) #1到20的奇数
for value in even_numbers:
    print(value)
    
special_numbers=list(range(3,31,3)) #3到30的里3的倍数
for value in special_numbers:
    print(value)
    
numbers_2=[]
for value in range(1,11):
    numbers_2.append(value**3)     #1到10的立方
print(numbers_2)

numbers_3=[value**3 for value in range(1,11)]#采用列表解析的方式
print(numbers_3)

4.4 使用列表的一部分

处理列表的部分元素-Python称为切片
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,不包含最后一个,指定索引0~3,将输出分别为0、1和2的元素。

players=['charles','martina','michael','florence','eli']
print(players[0:3])

[‘charles’, ‘martina’, ‘michael’]
如果没有指定第一个索引,Python将自动从列表开头开始:

players=['charles','martina','michael','florence','eli']
print(players[:4])

[‘charles’, ‘martina’, ‘michael’, ‘florence’]
要让切片终止于列表末尾,也可省略终止索引。
要遍历列表的部分元素,可在for循环中使用切片。

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

Here are the first three players on my team:
Charles
Martina
Michael
复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略其实索引和终止索引([:])。即复制整个列表

my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
my_foods.append('cannoli')
print(my_foods)
print(friend_foods)

[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
[‘pizza’, ‘falafel’, ‘carrot cake’]

my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods #直接赋值
my_foods.append('cannoli')
print(my_foods)
print(friend_foods)

[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]

这里将my_foods赋给friedns_foods,而不是将my_foods的副本存储到friend_foods。这种语法实际上时让Python将新变量friend_foods关联到包含在my_foods中的列表,因此两个变量都指向同一个列表。输出表明,两个列表时相同的。
注意:复制列表时,请确认使用切片复制了列表。
习题4-10~4-12

my_foods=['pizza','falafel','carrot cake','ice cream']
my_foods.append('cannoli')
print(my_foods)

print('\nThe first three items in the list are:')
print(my_foods[:3])
print('\nThree items from the middle of the list are:')
print(my_foods[1:4])
print('\nThe last three items in the list are:')
print(my_foods[2:])

friend_foods=my_foods[:]
my_foods.append('pizzaplus')
friend_foods.append('pepperoni')
print('\nmy favourite foods:')
for food in my_foods:
    print(food)
print("\nmy friend's favourite foods:")
for food in friend_foods:
    print(food)

4.5 元组

列表适合用于存储程序运行期间可能变化的数据集。然而,有时候你要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表成为元组。
元组看起来就像列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。

dimensions=(200,50)
for dimension in dimensions:
    print(dimension)

200
50
虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改,可重新定义整个元组

dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)

Original dimensions:
200
50

Modified dimensions:
400
100
如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。

Chapter 5 if语句

if …:
do something

age=12
if age<4:
    print('Your admission cost is 0')
elif age<18:
    print('Your admission cost is 5')
else:
    print("Your admission cost is 10")

Your admission cost is 5

练习5-3~5-7

alien_color=['yellow','blue']
if 'green' in alien_color:
    print('your score increased 5 points.')
elif 'yellow' not in alien_color:
    print('you got 10 points.')
else:
    print('Hah')
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!
练习题5-8~5-11

users=['admin','zhao','qian','sun','li'] #给不同人打招呼
if users!=[]:
    for user in users:
        if user=='admin':
            print('Hello admin, would you like to see a status report?')
        else:
            print('\nHello '+user+',thank you for logging in again')
else:
    print('We need to find some users!')
current_users=['admin','zhao','qian','sun','li']  #检查用户名是否被注册
current_users_lower=[]
for user in current_users:
    current_users_lower.append(user.lower())
    
new_users=['zhou','wu','Zheng','Sun','li']
if new_users!=[]:
    for user in new_users:
        if user.lower() in current_users_lower:
            print('You need to input another name')
        else:
            print('this name is perfect!')
numbers=list(range(1,10)) #输出1~9的序数词缩写
for value in numbers:
    if value == 1:
        print('1st')
    elif value == 2:
        print('2nd')
    elif value == 3:
        print('3rd')
    else:
        print(str(value)+'th')

Chapter 6 字典

在Python中,字典时一系列键-值对。每个键都与一个值相关联,你可以使用键来访问与之关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
在Python中,字典用放在花括号{}中的一系列键-值对表示。alien_0={'color': 'green', 'points': 5}
要获取与键相关联的值,可依次指定字典名和放在方括号内的值,如alien_0['color']这将返回green.
添加键-值对时,可依次指定字典名、用方括号括起的键和相关联的值。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 25}
Python不关心键-值对的添加顺序,而只关心键和值之间的关联关系。
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值

alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")

The alien is green.
The alien is now yellow.
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除。使用del 语句时,必须指定字典名和要删除的键。

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}
练习6-1

people = {
        'name': 'zhao',
        'age': 5,
        'city': 'London'
        }
print(people['name'])
print(people['age'])

遍历所有的键-值对

user_0 = {
        'username': 'efermi',
        'first': 'enrico',
        'last': 'fermi',
        }
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)

Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi
使用for …,… in …items():结构
在不需要使用字典中的值时,方法keys()很有用。

favorite_languages = {
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
如果你感兴趣的主要是字典包含的值,可使用方法values() ,它返回一个值列表,而不包含任何键。

favorite_languages = {
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

The following languages have been mentioned:
Python
C
Ruby
Python
为剔除重复项,可使用集合(set)。集合类似于列表,但每个元素都必须是独一无二的:

favorite_languages = {
        'jen': 'python',
        'sarah': 'c',
        'edward': 'ruby',
        'phil': 'python',
        }
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

The following languages have been mentioned:
C
Ruby
Python
通过对包含重复元素的列表调用set() ,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
练习6-5

rivers = {
        'nile': 'egypt',
        'Changjiang': 'china',
        'Danube':'Europe'
        }
for river,country in rivers.items():
    print('The ' + river +' runs through '+country)
for river in rivers.keys():
    print(river)
for country in rivers.values():
    print(country)

有时需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。
字典列表:

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
接下来生成30个外星人,并显示前5个外星人:

aliens=[]
for alien_number in range(30):
    new_alien={'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[:5]:
    print(alien)
print('...')
print('\nTotal number of aliens:' +str(len(aliens)))

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

Total number of aliens:30
所有外星人都是绿色的,但情况并总是如此,因此编写一条if 语句来确保只修改绿色外星人。如果外星人是绿色的,我们就将其颜色改为’yellow’ ,将其速度改为’medium’ ,并将其点数改为10:

aliens=[]
for alien_number in range(30):
    new_alien={'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['speed']='medium'
        alien['points']=10
        
for alien in aliens[0:5]:
    print(alien)
print('...')

{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

在字典中存储列表

pizza = {
        'crust': 'thick',
        'toppings': ['mushrooms','extra cheese'],
        }
print('you ordered a '+pizza['crust']+'-crust pizza '+
      'with the following toppings:')
for topping in pizza['toppings']:
    print('\t'+topping)

you ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。
当我们遍历字典时,与每个被调查者相关联的都是一个语言列表,而不是一种语言;因此在遍历该字典的for 循环中,我们需要再使
用一个for 循环来遍历与被调查者相关联的语言列表:

favorite_languages = {
        'jen':['python','ruby'],
        'sarah':['c'],
        'edward':['ruby','go'],
        'phil':['python','haskell'],
        }
for name,languages in favorite_languages.items():
    if len(languages)==1:
        print("\n"+name.title()+"'s favorite language is:")
    else:
        print("\n"+name.title()+"'s favorite languages are:")
    for language in languages:
        print("\t"+language.title())

Jen’s favorite languages are:
Python
Ruby

Sarah’s favorite language is:
C

Edward’s favorite languages are:
Ruby
Go

Phil’s favorite languages are:
Python
Haskell
在字典中存储字典,例如,如果有多个网站用户,每个都有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在
一个字典中,并将该字典作为与用户名相关联的值。

users = {
        'aeinstein':{
                'first':'albert',
                'last':'einstein',
                'location':'princeton'
                },
                
        'mcurie':{
                'first':'marie',
                'last':'curie',
                'location':'paris',
                },
        }
for username,user_info in users.items():
    print("\nUsername: "+username)
    full_name=user_info['first']+" "+user_info['last']
    location=user_info['location']
    print("\tFull name: "+full_name.title())
    print("\tLocation: "+location.title())

Username: aeinstein
Full name: Albert Einstein
Location: Princeton

Username: mcurie
Full name: Marie Curie
Location: Paris
注意,表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更容易。倘若表示每位用户的字典都包含不同的键,for 循环内部的代码将更复杂。
练习题6-10~6-12

cats={'cat':'liu'}  #宠物
dogs={'dog','wang'}
pets=[cats,dogs]
for pet in pets:
    print(pet)
favorite_places = {
        'zhao':['tokyo','chongqing','shanghai'],      #喜欢的地方
        'liu': ['hongkong','chongqing','beijing'],
        'qian': ['new york','vietnam','jinan'],
        }
for name,places in favorite_places.items():
    print("\nname:"+name)
    for place in places:
        print(place)
cities={
        'hangzhou':{        #城市
                'country': 'china',
                'population': 10000,
                'fact':'beauty',
                },
        'sydney':{
                'country':'Australia',
                'population': 20000,
                'fact':'large',
                },
        'tokyo':{
                'country':'japan',
                'population':30000,
                'fact':'small',
                }
        }

for city,info in cities.items():
    print("\ncity:"+city)
    print("\ncountry: "+info['country'])
    print("population: "+str(info['population']))
    print("fact: "+info['fact'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值