文章目录
概述
本章内容主要学习了列表和元组;通过本节课,理解了python中为什么万物皆对象。
列表(list)
列表是Python中的有序、可变数列。
列表可以放入不同类型的变量。
primes = [2, 3, 5, 7]
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
hands = [
['J', 'Q', 'K'],
['2', '2', '2'],
['6', 'A', 'K'], # (Comma after the last element is optional)最后一个元素的逗号是可有可无的。
]
# (I could also have written this on one line, but it can get hard to read)
hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]
#列表也可以放入很多不同类型的变量
my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)
1. 索引(indexing)
我们可以用方括号访问列表中某一单个元素。
Python使用从0开始的索引,所以第一个元素对应索引0。
可以通过负数索引从后往前访问列表。
planets[0] # 'Mercury'
planets[1] # 'Venus'
planets[-1] # 'Neptune'
planets[-2] # 'Uranus'
2. 切片(slicing)
planets[0:3]
是访问列表planets
中从索引0开始,到索引3的全部元素,这里不包括索引3本身。
planets[0:3] # ['Mercury', 'Venus', 'Earth']
切片时,开始和结束的索引都是可选的,我们也可以省略开始和结束是对应的第一个(0)或最后一个索引(列表的长度)。
planets[:3] # ['Mercury', 'Venus', 'Earth']
planets[3:] # ['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] # 这里表达的是从索引3开始,之后所有元素。
当切片时,我们也可以用负索引。
planets[1:-1] # 除了第一个和最后一个的全部行星
# ['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']
planets[-3:] # 最后三个行星
# ['Saturn', 'Uranus', 'Neptune']
3. 改变列表(Changing lists)
列表是可变的(“mutable”),他们可以在恰当的(“in place”)的位置被修改。
一种修改列表的方法是给索引或者切片赋值。
planets[3] = 'Malacandra'
planets
'''
['Mercury',
'Venus',
'Earth',
'Malacandra',
'Jupiter',
'Saturn',
'Uranus',
'Neptune']
'''
planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
# ['Mur', 'Vee', 'Ur', 'Malacandra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
# That was silly. Let's give them back their old names
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
4. 列表方程(List functions)
-
len
给出列表长度# How many planets are there? len(planets) # 8
-
sort
返回一个经过排序后的列表。# The planets sorted in alphabetical order sorted(planets) # ['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']
-
sum
,max
,min
primes = [2, 3, 5, 7] sum(primes) # 17 max(primes) # 7
5. 插曲:对象(objects)
Everything in Python is object.
objects 包含一些东西,我们可以通过Python点语法(dot syntax)调用。
例如,数字(numbers)携带一个相关变量,叫imag
,他代表数字的虚部 (imaginary part) 。(You’ll probably never need to use this unless you’re doing some very weird math.)
x = 12
# x is a real number, so its imaginary part is 0.
print(x.imag)
# Here's how to make a complex number, in case you've ever been curious:
c = 12 + 3j
print(c.imag)
'''
0
3.0
'''
- object中包含的事物可以是函数(function)。附属于一个对象的函数叫做方法(method)。 (Non-function things attached to an object, such as
imag
, are called attributes).
例如,数字有一个方法叫做bit_length
,我们用点语法访问它。
x.bit_length
# <function int.bit_length()>
为了调用它,我们增加括号(parentheses):
x.bit_length()
# 4
我们也可以用help
函数查询(pass)方法:
help(x.bit_length)
'''
Help on built-in function bit_length:
bit_length() method of builtins.int instance
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
'''
上述方法的调用可能有些难以理解,我们不经常调用(numbers, functions, booleans) 的方法(method)或属性(attribute),接下来我们尝试我们经常使用的列表(list)的方法。
6. 列表方法(List methods)
list.append
通过向列表末尾添加项来修改列表
# Pluto is a planet darn it!
planets.append('Pluto')
为什么上述c单元格(cell)没有输出(output),让我们通过调用help(planets.append)
来查看文档说明。
顺便提及 :
append
是一种可以被所有list种类对象所调用的方法,不仅仅适用于列表planets
,我们可以调用help(list.append)
。然而,如果我们调用call(append)
,Python会输出没有变量的名字叫"append"。"append"这个名称只在lists对象中存在,它不会存在于一个像内置函数max
,min
一样的独立(standalone)名字中。
help(planets.append)
'''
Help on built-in function append:
append(object, /) method of builtins.list instance
Append object to the end of the list.
'''
- > None
告诉我们list.append
不返回任何东西,但是我们可以查看planets
的值,我们可以据此看到planets
通过append改变的值。
planets
'''
['Mercury',
'Venus',
'Earth',
'Mars',
'Jupiter',
'Saturn',
'Uranus',
'Neptune',
'Pluto']
'''
list.pop
:移除(remove)并返回(return)列表中最后一个元素。
planets.pop()
# output: 'Pluto'
planets
# ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
7. 列表的查询(searching list)
我们可以通过list.index
方法,获取某一值的索引。
planets.index('Earth')
# 2
# 'Earth'排在第三位(索引从0开始)
如果我们搜寻Pluto的索引在哪里呢?
planets.index('Pluto')
'''
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-3a8584cba91a> in <module>
----> 1 planets.index('Pluto')
ValueError: 'Pluto' is not in list
'''
我们发现’Pluto’不在列表中,为了避免这种错误的发生,我们可以用in
操作符去查看某一list中是否存在一特殊值。
# Is Earth a planet?
"Earth" in planets
# True
还有很多方法我们在这里没有提及,如果你需要学习某一特殊对象的所有方法和属性,我们对这个对象本身调用help()
。例如,help(planets)
将告诉我们所有的列表方法。
help(planets)
点击"output"按钮会看到一整夜的帮助内容。Lists have lots of methods with weird-looking names like __eq__
and __iadd__
. 不用担心有如此多的内容(其中大部分内容我们可能永远不会直接用到,但当我们在使用索引或比较操作符等语法时,它们会在幕后(scenes)被调用。)The most interesting methods are toward the bottom of the list (append
, clear
, copy
, etc.).
元组(Tuples)
元组基本上与列表相同,但他与列表基本上有两点不同。
-
创建他们的语法用圆括号而不是方括号
t = (1, 2, 3) t = 1, 2, 3 # equivalent to above t # (1,2,3)
-
元组不能被修改 (they are immutable)。
t[0] = 100 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-36-e6cf7836e708> in <module> ----> 1 t[0] = 100 TypeError: 'tuple' object does not support item assignment
元组通常用于具有多个返回值的函数。
例如,浮点数对象的as_integer_ratio()
方法,通过元组返回分子和分母两个变量。
x = 0.125
x.as_integer_ratio()
# (1, 8)
多个返回值可以按照如下方式单独分配:
numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
# 0.125
最后,下述是交换两个变量的技巧。
a = 1
b = 0
a, b = b, a
print(a, b)
# 0 1
返回值的函数。
例如,浮点数对象的as_integer_ratio()
方法,通过元组返回分子和分母两个变量。
x = 0.125
x.as_integer_ratio()
# (1, 8)
多个返回值可以按照如下方式单独分配:
numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
# 0.125
最后,下述是交换两个变量的技巧。
a = 1
b = 0
a, b = b, a
print(a, b)
# 0 1