zoukankan      html  css  js  c++  java
  • 练习34--获取列表元素

    一 相关知识

    1 索引的产生以及为什么python的列表索引是从0开始的?

    我们把这些能排序的数字叫做序数(ordinal numbers),因为它们能代表一定的顺序。
    《笨办法学python》:
           然而,程序不会这么想。它们能从一个列表中任意取出一个元素来。对程序而言,动物们的列表更像是一叠卡片。如果它们想要老虎,就直接去拿。如果想要斑马,也能直接去拿。这就需要这些元素能有一个恒定的地址(address),或者索引(index),以便程序能够以一种随机的方式把它们从列表中拿出来。最好的办法就是让指标(indices)从 0 开始。相信我,这样在数学上更为便捷。这种数字叫做基数(cardinal number),它意味着你可以随机取数,所以必须要有一个 0 元素。
    网上的一些答案:
            python的创始人bai(Guido van Rossum)说过,Python使用0-based索引方式的原因之一是Python的切片(slice)语法。
           先看看切片的用法。可能最常见的用法就是“从数组中切出前n位”或“从数值这第i位起切出n位”(前一种实际上是i==起始位的特殊用法)。如果使用这种语法时不需要表达成难看的+1或-1补充方式,那将是非常的优雅。
           使用0-based的索引方式,Python的半开区间切片和缺省匹配区间切片语法变得非常漂亮: a[:n] 和 a[i:i+n],前者的标准写法就是a[0:n]。
    如果是1-base的索引方式,那么,想让a[:n]表达成“取前n个元素”,(这是不行的),要么使用一个闭合区间切片语法,要么在切片语法中使用切片起始位和切片长度2个参数的形式。使用1-based索引方式,半开区间切片语法变得不优雅。这种方式下使用闭合区间切片语法,为了表达从第i位取n个元素时必须写出a[i:i+n-1]。这样看来,如果使用1-based的索引,使用切片起始位+长度的形式更合适。这样可以写成a[i:n]。事实上ABC语言就是这样做的——它使用了一个独特的表达方式,写成a@i|n。(注:ABC语言是Python的祖先之一)
           Guido van Rossum说想其是被半开区间语法的优雅迷住了。特别是当两个切片操作位置邻接时,第一个切片操作的终点索引值是第二个切片的起点索引值时,太漂亮了,无法舍弃。例如,想将一个数组以i,j两个点切成三部分——这三部分将会是a[:i],a[i:j]和a[:i]。

           这就是为什么python的创始人要让Python使用0-based的索引方式的原因。

    二 习题

    记住:序数 == 排序,第一;基数 == 随机卡片,0。( ordinal == ordered, 1st; cardinal == cards at random, 0. )
    animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus']
    使用完整的表述格式进行回答,例如: “The first (1st) animal is at 0 and is a bear.” 然后反过来说一遍: “The animal at 0 is the 1st animal and is a bear
    1 The animal at 1.
    2 The third (3rd) animal.
    3 The first (1st) animal.
    4 The animal at 3.
    5 The fifth (5th) animal.
    6 The animal at 2.
    7 The sixth (6th) animal.
    8 The animal at 4.

    结果:

    1 The animal at 1 is the 2nd animal and is python3.6.
    2 The third (3rd) animal is at 2 and is a peacock.
    3 The first (1st) animal is at 0 and is a bear.
    4 The animal at 3 is the 4th animal and is a kangaroo.
    5 The fifth (5th) animal is at 4 and is a whale.
    6 The animal at 2 is the 3rd animal and is a peacock.
    7 The sixth (6th) animal is at 5 and is a platypus.
    8 The animal at 4 is the 5th animal and is a whale.

    python验证

     1 >>> animals = ['bear','python3.6','peacock','kangaroo','whale','platypus']
     2 >>> animals[1]
     3 'python3.6'
     4 >>> animals[2]
     5 'peacock'
     6 >>> animals[0]
     7 'bear'
     8 >>> animals[3]
     9 'kangaroo'
    10 >>> animals[4]
    11 'whale'
    12 >>> animals[2]
    13 'peacock'
    14 >>> animals[5]
    15 'platypus'
    16 >>> animals[4]
    17 'whale'
    18 >>>
  • 相关阅读:
    字串变换
    重建道路
    poj3278 Catch That Cow
    机器人搬重物
    [HNOI2004]打鼹鼠
    曼哈顿距离
    邮票面值设计
    poj1101 The Game
    解决了一个堆破坏问题
    模型资源从无到有一条龙式体验
  • 原文地址:https://www.cnblogs.com/luoxun/p/13328619.html
Copyright © 2011-2022 走看看