zoukankan      html  css  js  c++  java
  • Python 第二章-列表和元组

    第二章-列表和元组

    2.0
          在Python中,最基本的数据结构是序列(sequence)。序列中的每个元素被分配一个序列号-即元素的位置,

    也称为索引。第一个索引是0,第二个是1,以此类推。


    2.1 序列概览

    Python一共有6种内建的序列

    {
        列表,元组,字符串,Unicode字符串,buffer对象和xrange对象

    }


    2.2通用序列操作

        所有序列类型都可以进行某些特定的操作,这些操作包括:索引(indexing),分片(sliceing),加(adding),乘(multiplying)以及检查某个元素是否属于序列的成员(成员资格)。除此之外,Python还有计算序列长度,找出最大元素和最小的内建函数。
       

    >>>strA="abcdef";
    >>>strA[0]
    'a' 
    >>>strA[-1]
    'f'
    >>>'Hello'[1]
    'e'
    >>> mark=input("aaaa:")[0]
    aaaa:55
    >>> mark
    '5'
        
        下面是输入一个日期,整理后输出(没有什么特出月份的判断啥的,就是为了理解语法)
    代码:
      
    months=[ 
    '1yue',
    '2yue',
    '3yue',
    '4yue',
    '5yue',
    '6yue',
    '7yue',
    '8yue',
    '9yue',
    '10yue',
    '11yue',
    '12yue',
    ]
    
    endings=['st','nd','rd'] + 17 *['th']
      +['st','nd','rd'] + 7 *['th']
      +['st']
    
    
    year = input("Year:")
    month = input("Month:(1-12)")
    day = input("Day:(1-31)")
    
    
    month_number = int(month) 
    day_number = int(day)  
    month_name=months[month_number-1]
    ordinal=day+endings[day_number-1]
    print(month_name + ' ' + ordinal + ' ' + year)
    input("Press<enter>")  
    
    运行结果:
    Year:1
    Month:(1-12)2
    Day:(1-31)3
    2yue 3rd 1
    Press<enter>
    
    
    <span style="font-size:18px;"><pre name="code" class="python">
    
    
    <strong><span style="font-size:18px;">2.2.2分片(有点类似cmd里面的字符串处理)
        分片就是对字符串进行截取处理,这个截取是很灵活的,不解释了,直接看例子吧。</span></span></strong>
    <strong><span style="font-size:18px;">
    </span></strong>
    1.优雅地捷径 >>> web='<a href="http://www.python.org">Python web site</a>' >>> web[9:3] '' >>> web[9:30] 'http://www.python.org' >>> web[32:-4] 'Python web site' >>> number=[1,2,3,4,5,6,7,8,9,10] >>> number[3:6] [4, 5, 6] >>> number[0:1] [1] >>> number[-3:-1] [8, 9] >>> number[-3:0] [] >>> number[-3:] [8, 9, 10] >>> number[3:] [4, 5, 6, 7, 8, 9, 10] >>> number[:3] [1, 2, 3] >>> number[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> print(number[:]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> 2.更大的步长 - 分片
    
    
    >>> number[0:10:1]
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> number[0:5:2]
    [1, 3, 5]
    >>> number[0:10:3]
    [1, 4, 7, 10]
    >>> number[3:6:3]
    [4]
    >>> number[::4]
    [1, 5, 9]
    >>> number[8:3:-1]
    [9, 8, 7, 6, 5]
    >>> number[3:8:1]
    [4, 5, 6, 7, 8]
    >>> number[10:0:-2]
    [10, 8, 6, 4, 2]
    >>> number[10:0]
    []
    >>> number[10:0:-2]
    [10, 8, 6, 4, 2]
    >>> number[0:10:-2]
    []
    >>> number[::-2]
    [10, 8, 6, 4, 2]
    >>> number[5::-2]
    [6, 4, 2]
    >>> number[5:]
    [6, 7, 8, 9, 10]
    >>> number[:5]
    [1, 2, 3, 4, 5]
    >>> number[:5:-2]
    [10, 8]
    >>> number[5::2]
    [6, 8, 10]
    >>> number[:5]
    [1, 2, 3, 4, 5]
    
    <strong><span style="font-size:18px;">    在这里要得到正确的分片结果需要动些脑筋。开始的元素(最左边元素)包括在结果之中,而结束点的元素(最右边的元素)则不在分片之内。当使用一个负数作为步长时,必须让开始点
    大于结束点。在没有明确指定开始点和结束点的时候,正负数的使用可能会带来一些混淆。不过在这种情况下Python会进行正确的操作:对于一个正数步长,Python会从序列的头部开始向右提取
    元素,直到最后一个元素;而对于负数步长,则是从序列的尾部开始向左提取元素,直到第一个元素。</span>
    
    <span style="font-size:18px;">2.2.3 序列相加
        通过使用加号可以进行序列的连接操作</span></strong>
    >>> [1,2,3]+[4,5,6]
    [1, 2, 3, 4, 5, 6]
    >>> 'Hellow' + 'World!'
    'HellowWorld!'
    >>> [1,2,3]+'world'
    Traceback (most recent call last):
     File "<pyshell#2>", line 1, in <module>
    [1,2,3]+'world'
    TypeError: can only concatenate list (not "str") to list
    
    <strong><span style="font-size:18px;">2.2.4乘法</span></strong>
    >>> 'asd'*5
    'asdasdasdasdasd'
    >>> [15]*5
    [15, 15, 15, 15, 15]
    >>> sequence=[None]*10
    >>> sequence
    [None, None, None, None, None, None, None, None, None, None]
    
    <strong><span style="font-size:18px;">例子:打印一个盒子,然后在里面打印一行字</span></strong>
    
    sentence=input("sentence:")
    screen_whdth=80
    text_width=len(sentence)
    box_width= text_width - 6
    left_margin = (screen_whdth - box_width) // 2
    print()
    print(' ' * left_margin + '+'  + '-'* (box_width - 2) +  '+')
    print(' ' * left_margin + '| ' + ' '* text_width      + ' |')
    print(' ' * left_margin + '| ' +       sentence       + ' |')
    print(' ' * left_margin + '| ' + ' '* text_width      + ' |')
    print(' ' * left_margin + '+'  + '-'* (box_width - 2) +  '+')
    print()
    
    <strong><span style="font-size:18px;">ps:效果特别不好,书上没算准,懒得去改了,就是想熟悉下语法,实现结果不重要</span>
    <span style="font-size:18px;">
    2.2.5成员资格(in 判断成员是不是在序列中)</span></strong>
    permissions='rw'
    'w' in permissions
    'x' in permissions
    users=['mlh' ,'foo' ,'bar']
    input('enter your user name:') in users
    subjuce='aada Get rich now!!! aada'
    'aaa' in subjuce
    
    <strong><span style="font-size:18px;">例子
          #检查用户名和PIN码 
     
    代码
    </span></strong>
    database = [
      ['albert' ,'1234'],
      ['sdfddd' ,'2345'],
      ['sdsddd' ,'4567'],
      ['sdasaw' ,'8658'],
    ]
    username = input('User Name:')
    pin = input('Pin code: ')
    if([username,pin] in database):
    print("ok")
    else:
    print("no");
    
    结果 
    >>> 
    User Name:albert
    Pin code: 1234
    ok
    >>> 
       
    <strong><span style="font-size:18px;">2.2.6  列表的长度、最小值和最大值</span></strong>
    numbers = [100,34,678]
    len(numbers)
    max(numbers)
    min(numbers)
    max(2,3);
    min(9,3,2,5)
    
    <strong><span style="font-size:18px;">2.3 列表:Python的"苦力"
    列表不同于元组和字符串,列表本身是可以修改的,同时有它专门的好用的方法。
    
    2.3.1 list函数
    字符串创建列表</span></strong>
    >>> list("Hello")
    ['H', 'e', 'l', 'l', 'o']
    >>> aa = list("Hello")
    >>> aa*3
    ['H', 'e', 'l', 'l', 'o', 'H', 'e', 'l', 'l', 'o', 'H', 'e', 'l', 'l', 'o']
    >>> 
    
    <strong><span style="font-size:18px;">2.3.2 基本的列表操作</span>
    
    <span style="font-size:18px;">1.列表是可修改的</span></strong>
    x=[1,1,1]
    x[1] = 2
    print(x)
    [1, 2, 1]
    
    <strong><span style="font-size:18px;">2.删除元素</span></strong>
    [1, 2, 1]
    >>> name = ['1' ,'2' ,'3']
    >>> name
    ['1', '2', '3']
    >>> del name[1]
    >>> name
    ['1', '3']
    >>> 
    
    <strong><span style="font-size:18px;">3.分片赋值
    例子</span></strong>
    name=list('Perl')
    print(name)
    name[2:]=list('ar')
    print(name)
    结果
       >>> 
    ['P', 'e', 'r', 'l']
    ['P', 'e', 'a', 'r']
    >>> 
    
    <strong><span style="font-size:18px;">4.不等长替换</span></strong>
    name=list('Perl');
    name[1:] = list("ython");
    print(name);
    
    
    <strong><span style="font-size:18px;">5.插入元素</span></strong>
    numbers=[1,5];
    numbers[1:1] = [2,3,4];
    print(numbers);
    
    
    <strong><span style="font-size:18px;">6通过替换删除片段</span></strong>
    numbers[1:4] = [];
    print(numbers);
    
    
    <strong><span style="font-size:18px;">7.del删除片段</span></strong>
    numbers = [1,2,3,4,5];
    del numbers[1:2];
    print(numbers);
    
    <strong><span style="font-size:18px;">2.3.3 列表方法
    #1.append 在列表末端追加新对象</span></strong>
    lst = [1,2,3]
    lst.append(4)
    print(lst)
    
    
    #2.count 方法统计某个元素在列表中出现的次数
    print(['to','be','or','not','to','be'].count('to'));
    x = [[1,2],1,1,[2,1,[1,2]]]
    print(x.count(1));
    print(x.count([1,2]));
    
    #3.extend方法可以在列表末尾一次性追加另一个序列中的多个值,用一个列表扩充另一个列表
    a = [1 ,2 ,3];
    b = [4 ,5 ,6];
    a.extend(b);
    print(a);
    <strong><span style="font-size:18px;">#ps: a=a+b 的效率比a.extend(b)低,这个不解释了,很好理解,a=a+b要创建副本
    
    #4.index 从列表中找出某个第一次匹配项的索引位置</span></strong>
    knights = ['we' ,'are' ,'the' ,'knights' ,'who' ,'say' ,'ni'];
    x = knights.index('who');
    print(x);
    x = knights.index('ss');
    print(x);
    输出:
    4
    Traceback (most recent call last):
     File "C:/Users/King/Desktop/s.py", line 5, in <module>
    x = knights.index('ss');
    ValueError: 'ss' is not in list
    >>> 
    <strong><span style="font-size:18px;">ps:找不到就异常了,额...感觉不是很科学
    #5.insert 方法用于将对象插入到列表中</span></strong>
    >>> numbers = [1,2,3,4,5,6,7]
    >>> numbers.insert(3,'four')
    >>> numbers
    [1, 2, 3, 'four', 4, 5, 6, 7]
    >>> #等价于
    >>> numbers = [1,2,3,4,5,6,7]
    >>> numbers[3:3] = ['four']
    >>> numbers
    [1, 2, 3, 'four', 4, 5, 6, 7]
    >>> #但是没有insert直观
    >>> 
    
    <strong><span style="font-size:18px;">#6.pop 从列表尾部取出一个值 出栈
    #Python里 列表+append+pop 可以模拟出来一个栈</span></strong>
    x = [1 ,2, 3]
    x.append(x.pop())
    print(x)
    [1,2,3]
    <strong><span style="font-size:18px;">#ps: 如果想模拟队列就用 inset(0,...) pop(0)
    
    #7.remove 方法用于溢出列表中某个值得第一个匹配项</span></strong>
    x = ['to' ,'be' ,'or' ,'not' ,'to' ,'be'];
    x.remove('be');
    print(x);
    x.remove('bee');
    <strong><span style="font-size:18px;">#移除不存在的依然报错
    
    #8.reverse 方法将列表中的元素反向存放</span></strong>
    x = [1,2,3];
    x.reverse();
    print(x);
    <strong><span style="font-size:18px;">#ps 如果需要对一个序列进行反向迭代,那么可以使用reversed函数,这个函数并不会返回
    #一个列表,而是返回一个迭代器(iterator)对象,尽管如此,使用list函数把返回的对象
    #转换成列表也是可行的:</span></strong>
    x = [1 ,2 ,3];
    print(list(reversed(x)));
    
    <strong><span style="font-size:18px;">#9.sort排序</span></strong>
    1.
    >>> x = [5 ,4 ,3 ,2 ,1]
    >>> y = x
    >>> x.sort()
    >>> x
    [1, 2, 3, 4, 5]
    >>> y
    [1, 2, 3, 4, 5]
    >>> 
    2.
    >>> x = [3 ,2 ,1]
    >>> y = x[:]
    >>> x.sort()
    >>> x
    [1, 2, 3]
    >>> y
    [3, 2, 1]
    >>> 
    <strong><span style="font-size:18px;">3.sorted函数</span></strong>
    >>> x = [5 ,4 ,3 ,2 ,1]
    >>> y = sorted(x)
    >>> x
    [5, 4, 3, 2, 1]
    >>> y
    [1, 2, 3, 4, 5]
    >>> 
    <strong><span style="font-size:18px;">4.从大到小</span></strong>
    >>> x = [5 ,2 ,3 ,4]
    >>> x.sort()
    >>> x.reverse()
    >>> x
    [5, 4, 3, 2]
    >>> 
    <strong><span style="font-size:18px;">ps:也可以 sorted(x).reverse() ,但是x.sort().reverse()不行,因为x.sort()返回None,不能排序
    
    #10.高级排序 
      1.首先,类似于c++里面的那个sort函数支持的cmp一样,这个也支持</span></strong>
      numbers = [5 ,2 ,9 ,7];
      numbers.sort(cmp);
      numbers
      [2 ,5 ,9 ,7]
      <strong><span style="font-size:18px;">ps:前提是定义好cmp函数,不然运行出错,这个后面说</span></strong>
    <strong><span style="font-size:18px;">
      2.还有两个可选参数 key和reverse  一个是排序依据(key有点cmp的意思),另一个是方向</span></strong>
    >>> x = ['111' ,'23213' ,'3']
    >>> x.sort(key=len)
    >>> x
    ['3', '111', '23213']
    >>> x.sort()
    >>> x
    ['111', '23213', '3']
    >>> x.sort(reverse=True)
    >>> x
    ['3', '23213', '111']
    >>> 
    <strong><span style="font-size:18px;">
    2.4元组是不能改变的列表,单个后面必须有,而且通常()包起来</span></strong>
    >>> 1,2,3
    (1, 2, 3)
    >>> (1,2,3)
    (1, 2, 3)
    >>> ()
    ()
    >>> ()*10
    ()
    >>> (1,)*10
    (1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    >>> 3*(40+2)
    126
    >>> 3*(40+2,)
    (42, 42, 42)
    >>> 
    2.4.1 tuple函数,把序列转成元组
      >>> tuple([1,2,3])
    (1, 2, 3)
    >>> tuple((1,2,3))
    (1, 2, 3)
    >>> 
    
    <strong><span style="font-size:18px;">2.4.2 元组的基本操作
         元组本身并不复杂,除了创建和访问之外没啥别的</span></strong>
    >>> x = 1,2,3
    >>> x
    (1, 2, 3)
    >>> y=(1,2,3);
    >>> y[0:2]
    (1, 2)
    >>> 

    2.4.3 那么,元组到底有卵用?

    1.元组可以在映射(和集合的成员)中当做键使用-而列表不行。
    2.元组作为很多内建函数的返回值存在,也就是说必须对元组进行处理,只要不尝试修改元组,那么"处理"元组在绝大多数情况下就是把他们当做列表进行操作。一般来说,列表肯能更能满足对序列的所有需求。

     ps:

             我X,看了这两个不是理由的理由,真是觉得元组本身没什么卵用。只是没办法才使用,本来以为只读的有什么高效的地方。

      
      
     
  • 相关阅读:
    IssueQuery failed in redmine rake tasks
    rubymine 调试 redmine
    redmine rake tasks
    rails tutorial sample app
    win7 chm 打开失败记录
    rails再体验(第一个程序)
    Bitnami Redmine插件开发记录
    redmine export long csv file failed: 502 proxy error
    Java时区切换时的需要注意
    Android No static field XXX of type I in class Lcom/XXX/R$id错
  • 原文地址:https://www.cnblogs.com/csnd/p/12062371.html
Copyright © 2011-2022 走看看