Lists —— Python 4/7
本章讲述列表(Lists)及其相关操作,包括索引,分割和变形。
Lists
- 在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)
索引
- 你可以用方括号访问列表的某个元素;
- 哪个行星是离太阳最近的?Python使用0基准索引,所以第一个元素的下标是0。
planets[0]
'Mercury'
- 下一个最近的行星呢?
planets[1]
'Venus'
- 哪个行星离太阳最远?
- 列表中的最后的元素可以通过负下标获得,从-1开始;
planets[-1]
'Neptune'
planets[-2]
'Uranus'
分割
- 前三个行星是哪些?这就需要用到分割:
planets[0:3]
['Mercury', 'Venus', 'Earth']
planets[0:3]
是我们查找从0开始到3(但不包括3)的元素的一种方式。- 起始索引和结束索引均可选。如果我不写起始索引,它假定为0。所以我可以重写上面的表达式为:
planets[:3]
['Mercury', 'Venus', 'Earth']
- 如果我不写结束索引,它假设是列表的长度;
planets[3:]
['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
- 也就是说,上面的叙述意思是“列出从第三个开始的所有行星”
- 我们也可以用负下标来分割:
# All the planets except the first and last
planets[1:-1]
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']
# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']
改变列表的值
- 列表是可变的,也就是说他们可以“就地”修改;
- 修改列表的方法之一是分配给索引或片段表达式。
- 例如我们重命名Mars
planets[3] = 'Malacandra'
planets
['Mercury',
'Venus',
'Earth',
'Malacandra',
'Jupiter',
'Saturn',
'Uranus',
'Neptune']
- emm,读着挺绕口的,我们来吧前三个行星的名字都缩短吧。
planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets)
# That was silly. Let's give them back their old names
planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
['Mur', 'Vee', 'Ur', 'Malacandra', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
列表相关函数
Python有很多操作列表的函数
len
给出列表的长度
# How many planets are there?
len(planets)
8
sorted
返回列表排序后的版本
# The planets sorted in alphabetical order
sorted(planets)
['Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 'Uranus', 'Venus']
sum
求和
primes = [2, 3, 5, 7]
sum(primes)
17
- 我们以前使用min和max获取几个参数中的最小或最大值。但我们也可以在参数中传递一个列表。
max(primes)
7
题外话:对象
- 到此为止,我使用了很多次术语’object’。你可能已经读过,Python的一切都是对象。什么意思?
- 总之,对象携带一些与他们相关的事物。你访问使用Python的点运算。
- 例如,Python中数字携带者一个相关变量叫
imag
代表着他们的虚部。(我可能永远用不上这个除非你在做一些奇怪的运算)。
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
- 对象携带的相关信息也包括函数。一个对象相关的函数称方法。(对象携带着的非函数的东西称属性)。
- 例如,数字有一个方法称
bit_length
。同样的我们可以通过点运算访问:
x.bit_length
<function int.bit_length()>
- 要想真正调用它,我们要加上括号
x.bit_length()
4
- 同样我们可以将函数传到
help
函数中,我们也可以传方法:
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
- 上面的例子已经十分清楚了。我们已经看过的类型对应的对象(数字,函数,布尔值)包含你需要用的属性和方法。
- 但是列表有一些方法是你一直要使用的。
列表的方法
list.append
通过在列表末尾添加项目来修改列表。
# Pluto is a planet darn it!
planets.append('Pluto')
- 为什么上面的代码块没有输出?,我们来看看文档
注:
append
是一个携带所有所有类型对象的列表方法,不只是planets
这个列表,我们也可以用help(list.append)
。然而,如果我们调用help(append)
,python会报错说没有变量叫”append“。”append“只存在在list对象中,他不像标准内置函数如max
和len
。
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
['Mercury',
'Venus',
'Earth',
'Mars',
'Jupiter',
'Saturn',
'Uranus',
'Neptune',
'Pluto']
list.pop
移除并销毁列表的最后一个元素。
planets.pop()
'Pluto'
planets
['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
搜索列表
- 地球是行星中的第几个? 我们可以通过
list.index
方法获得他的下标
planets.index('Earth')
2
- 第三个(从零开始)
- Pluto呢?
planets.index('Pluto')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_20/2263615293.py in <module>
----> 1 planets.index('Pluto')
ValueError: 'Pluto' is not in list
- 哦对……
- 为了像这样的避免不愉快的惊吓,我们可以用
in
运算符来决定是否一个列表包含一个指定的值。
# Is Earth a planet?
"Earth" in planets
True
# Is Calbefraques a planet?
"Calbefraques" in planets
False
- 还有几个有趣的我们没有涵盖的列表方法。如果你想了解的所有方法和属性附加到特定对象,我们可以调用
help()
对象本身。例如,help(planets)
会告诉我们关于列表所有方法:
help(planets)
Help on list object:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Stable sort *IN PLACE*.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
元组
元组几乎和列表完全一样,只是两点不同:
- 创建元组的符号使用圆括号
t = (1, 2, 3)
t = 1, 2, 3 # equivalent to above
t
(1, 2, 3)
- 他们不可以被修改(是不可变的)
t[0] = 100
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_20/816329950.py 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
- 最后我们可以看下经典的Python 技巧来交换两个变量。
a = 1
b = 0
a, b = b, a
print(a, b)
0 1