Python培训(3)

明天和同事共享的主题为,主要是较为复杂的Python数据类型,

列表(List)
元组(Tuple)
字典(Dictionary)
列表/字典/元组的嵌套


除了列表/元组/字典,Python变量类型还包括数字/字符串。

提醒一点,Python语言不指定变量类型,x=1(整型) 和 x=1.0(浮点型 )代表不同的数据类型,这会对运算结果造成影响,需要保持警惕。


先看列表。

列表由一系列按特定顺序排列的元素组成
Python 中,用方括号( [] )来表示列表,并用逗号来分隔其中的元素。
示例代码如下,

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)


列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉 Python 即可
访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内
Python 中,第一个列表元素的索引为 0 ,而不是 1
下面示例代码的输出结果是
trek
specialized
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
print(bicycles[3])

修改列表元素的语法与访问列表元素的语法类似
修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
示例代码如下,
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles[0] = 'ducati'
print(motorcycles)

•在列表末尾添加元素,可以用append
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles.append('ducati')
print(motorcycles)

•在列表中插入元素,可以用insert
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)

删除列表元素,可以用del或者pop().

如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;

如果你要在删除元素后还能继续使用它,就使用方法pop()

示例代码分别如下,
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

del motorcycles[0]
print(motorcycles)

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

也可以根据元素值删除,使用remove(),注意  方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)

motorcycles.remove('ducati')
print(motorcycles)

•使用方法sort()对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

•还可以按与字母顺序相反的顺序排列列表元素
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

•使用函数sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)

•倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)

cars.reverse()
print(cars)

•使用for循环来打印魔术师名单中的所有名字:
magicians = ['alice', 'david', 'carolina'] 
for magician in magicians:
    print(magician)
•思考:如何使用while循环遍历列表?

•列表切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

•如果没有指定第一个索引,Python将自动从列表开头开始:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])

•要让切片终止于列表末尾,也可使用类似的语法。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
•如果要输出名单上的最后三名队员,可使用切片players[-3:]

•如果要遍历列表的部分元素,可在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())


复制 列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引( [:]
Python 创建一个始于第一个元素,终止于最后一个元素的切片,即复制 整个列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]  # 思考:如果改成friend_foods = my_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中的一个元素,结果总是出错的:
dimensions = (200, 50)
dimensions[0] = 250
运行结果如下,
Traceback (most recent call last):
  File "dimensions.py", line 3, in <module>
    dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment

遍历元组中的所有值,示例代码如下,
dimensions = (200, 50)
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)


下面再看看 字典

字典是另一种可变容器模型,且可存储任意类型对象
字典的每个键值 (key=>value) 对用冒号 ( : ) 分割,每个对之间用逗号 ( , ) 分割,整个字典包括在花括号 ( {}) , 格式如下所示
d= {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
alien_0 = {'color': 'green', 'points': 5}

print(alien_0['color'])
print(alien_0['points'])


•访问字典中的值,要获取与键相关联的值,可依次指定字典名和放在方括号内的键,
alien_0 = {'color': 'green', 'points': 5}

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")

•字典是一种动态结构,可随时在其中添加键—值对。
•要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值。
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

•创建一个空字典,可先使用一对空的花括号定义一个字典,再分行添加各个键—值对
alien_0 = {}

alien_0['color'] = 'green'
alien_0['points'] = 5

print(alien_0)


•要修改字典中的值,可依次指定字典名、用方括号括起的键以及   与该键相关联的新值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")

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

对于字典中不再需要的信息,可使用 del 语句将相应的键 值对彻底删除
使用 del 语句时,必须指定字典名和要删除的键。
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)

del alien_0['points']
print(alien_0)

•遍历所有的键—值对
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + ".")

•遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name in favorite_languages.keys():
    print(name.title())

•遍历字典中的所有值
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())


最后,再看看列表/元组/字典的嵌套

有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
可以 在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典

字典和列表的嵌套,示例代码如下,
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)


在字典中存储列表,示例代码如下,
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}

for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())


在字典中存储列表
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}

for name, languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值