输出列表中元素的方法

今天看了https://featherl.gitee.io的博文,受益良多

以下是我根据 https://blog.csdn.net/lonely_feather/article/details/86363896 一文总结

 

一     输出列表中所有元素的方法
>>> list1=[5,8,'hello','A']

  1. 最简单的方法
    >>> list1=[5,8,'hello','A']
    >>> print(list1)
    [5, 8, 'hello', 'A']

     

  2. 对列表进行解包
    >>> list1=[5,8,'hello','A']
    >>> a,b,c,d=list1
    >>> a,b,c,d
    (5, 8, 'hello', 'A')

     

  3. 用列表名索引
    >>> list1=['5,','8,','hello,','A']
    >>> print(list1[0]+list1[1]+list1[2]+list1[3])
    5,8,hello,A

    注意:

    >>> list1=[5,8,'hello','A']
    >>> print(list1[0]+list1[1]+list1[2]+list1[3])
    Traceback (most recent call last):
      File "<pyshell#42>", line 1, in <module>
        print(list1[0]+list1[1]+list1[2]+list1[3])
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

    二     输出列表中个别元素的方法

        1.用列表名索引

  1. >>> list1=[5,8,'hello','A']
    >>> print(list1[0])
    5
    >>> print(list1[1])
    8
    >>> print(list1[2])
    hello
    >>> print(list1[3])
    A

    2.对列表进行解包

    >>> list1=[5,8,'hello','A']
    >>> a,b,c,d=list1
    >>> a
    5
    >>> b
    8
    >>> c
    'hello'
    >>> d
    'A'

     


版权声明:本文为qq_44455474原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。