Python学习之归纳
Table of Contents
1 列表
1.1 构成
由一系列按特定顺序排列的元素组成。用方括号([ ])表示列表,并用逗号分隔其中的元素。
bicycles.py bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles)
1.2 访问
列表是有序集合,因此要访问列表的任何元素,只需告知位置或索引。 也可使用title方法,使得输出更加整洁。
1.2.1 索引之特点
Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,可让Python返回最后一个列表元素
1.3 修添删元素
1.3.1 修改元素
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles)”
1.3.2 添加元素 – append方法、insert方法
# 末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
# 列表中添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
1.3.3 删除元素 – del方法、pop方法、remove方法
# del方法 -- 当知道要删除的元素在列表中的位置,则可以使用del语句
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
# pop方法 -- 将元素从列表中删除,并接着要使用它的值。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
# pop方法用法2 -- 从列表中任何位置中删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# remove方法 -- 根据要删除的元素的值,可据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
1.4 组织列表 – sort方法、sorted方法、reverse方法、len方法
# sort方法 -- 较轻松地对列表进行排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)”
# sort方法 -- 逆序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
# sorted方法 --  为保留列表元素原来的排列顺序,但输出的时候以特定的顺序呈现它们
# 若要逆序,上同sort方法
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))  
# reverse方法 -- 反转列表元素的排列顺序,非排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
# len方法 -- 可快速获悉列表的长度
>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4
1.5 遍历列表 – 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 everyone, that was a great magic show!")
1.6 创建数值列表 – range方法、list方法
值得关注的一点是range不仅仅可以生成数字元素,还可以指定步长 以及列表解析这一概念
even_numbers = list(range(2,11,2) print(even_numbers) squares = [value**2 for value in range(1,11)] print(squares)
2 __name__
一言以蔽之,__name__打印当前模块名。若当前模块被直接运行时,模块名为__main__.. 若模块被导入时import xxx,模块名 = xxx