4、python列表

列表和你可以用它们做的事情。包括索引,切片和变异!

文章目录

  • 1.列表
    • 1.1索引
    • 1.2切片
    • 1.3列表修改
    • 1.4列表函数
    • 1.5插曲:对象
    • 1.6列表方法
      • 1.6.1列表搜索
    • 1.7Tuples元组

1.列表

Python 中的 List 表示有序的值序列:

In [1]:

primes = [2, 3, 5, 7]

我们可以把其他类型的事情列入清单:

In [2]:

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

我们甚至可以列一个清单:

In [3]:

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']]

列表可以包含不同类型的变量:

In [4]:

my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)

1.1索引

可以使用方括号访问单个列表元素。

哪个行星离太阳最近? Python 使用从零开始的索引,因此第一个元素的索引为0。

In [5]:

planets[0]

Out[5]:

'Mercury'

下一个最近的星球是什么?

In [6]:

planets[1]

Out[6]:

'Venus'

哪个行星离太阳最远?

列表末尾的元素可以用负数访问,从 -1开始:

In [7]:

planets[-1]

Out[7]:

'Neptune'

In [8]:

planets[-2]

Out[8]:

'Uranus'

1.2切片

前三颗行星是什么? 我们可以通过切片来回答这个问题:

In [9]:

planets[0:3]

Out[9]:

['Mercury', 'Venus', 'Earth']

planets[0:3] 是我们询问从索引 0 开始并一直到 但不包括 索引 3 的方式。

起始和结束索引都是可选的。如果省略起始索引,则假定为 0。因此,我可以将上面的表达式重写为:

In [10]:

planets[:3]

Out[10]:

['Mercury', 'Venus', 'Earth']

如果我省略了结束索引,它被假定为列表的长度。

In [11]:

planets[3:]

Out[11]:

['Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

也就是说,上面的表达意思是“给我从索引3开始的所有行星”。

我们还可以在切片时使用负指数:

In [12]:

# All the planets except the first and last
planets[1:-1]

Out[12]:

['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']

In [13]:

# The last 3 planets
planets[-3:]

Out[13]:

['Saturn', 'Uranus', 'Neptune']

1.3列表修改

列表是“可变的”,这意味着它们可以“就地”修改。

修改列表的一种方法是为索引或片表达式赋值。

例如,假设我们想重命名火星:

In [14]:

planets[3] = 'Malacandra'
planets

Out[14]:

['Mercury',
 'Venus',
 'Earth',
 'Malacandra',
 'Jupiter',
 'Saturn',
 'Uranus',
 'Neptune']

嗯,这是相当拗口。让我们通过缩短前三个行星的名称来补偿。

In [15]:

planets[:3] = ['Mur', 'Vee', 'Ur']
print(planets

你可能感兴趣的:(从零开始的Python之旅,python,windows,服务器)