[每日一讲] Python系列:列表与元组

参考文档 https://docs.python.org/zh-cn/3.7/tutorial/introduction.html#lists

"""
DATA STRUCTURE
Container: Sequence
—— String、List & Tuple
List can be Changed or Updated. But, Tuple can not be.
To define a list, you can use symbol '[ ]', tuple use symbol '( )'

数据结构
容器:序列
—— 字符串、列表 & 元组
列表是可变序列。而元组不可以。
定义一个列表,可以使用符号'[ ]',元组则使用符号'( )'

"""


列表的用法

  • 作为 list 用
    见演示代码

  • 作为队列用
    队列 (queue) 作为一种线性的数据结构,其特点是 FIFO (先进先出),队列只能在队头做删除操作,在队尾做插入操作。
    在 Python 中,如果需要用到队列,则需要使用 collections.deque() 。deque 为双端队列,即在队头和队尾均可进行插入或删除操作。

  • 作为栈用
    栈(stack) 作为一种线性的数据结构,其特点是 FILO (先进后出),其限定只能在栈顶进行插入和删除操作。
    栈顶与栈底:允许元素插入与删除的一端称为栈顶,另一端称为栈底。
    压栈:栈的插入操作,叫做进栈,也称压栈、入栈。
    弹栈:栈的删除操作,也叫做出栈。
    在 Python 中,使用 list.append() 即为压栈;使用 list.pop() 即为出栈,注意该方法是返回出栈的内容。


演示代码

#! /usr/bin/python
# coding:utf-8


class ListAction:

    def __init__(self):
        pass

    @staticmethod
    def list_init():
        greeting = [None]
        print(greeting)

    @staticmethod
    def list_index():

        # note: Do not be out of range
        # 注意:别越界
        greeting = 'hello'
        print(greeting[0])

    @staticmethod
    def list_slicing():
        greeting = 'hello'
        print(greeting[2:3])

    @staticmethod
    def list_slicing_step():
        # note: the third num means the step.The num is 1 Default.
        # 注意:第三位数意味着步长,默认步长为1
        greeting = 'hello'
        print(greeting[::2])

    @staticmethod
    def list_connect():
        greeting = 'hello'
        friend = 'world'
        print(greeting + '' + friend)

    @staticmethod
    def list_repeat():
        greeting = 'hello'
        print(greeting * 3)

    @staticmethod
    def list_in():
        greeting = input("Input one character:")
        if 'o' in str(greeting):
            print(True)
        elif 'O' not in str(greeting):
            print('O is not in the list')
        else:
            print('Input character O')

    @staticmethod
    def list_length():
        greeting = input("Input something,I can calculate the length:")
        # 字符串拼接。注意类型须相同
        print('OK, Length is' + ' ' + str(len(greeting)))

    @staticmethod
    def to_list(para):
        print(list(para))

    @staticmethod
    def list_to_string(lst):
        try:
            to_string = ''.join(lst)
            print(to_string)
        except TypeError:
            print('must be string-list')

    @staticmethod
    def act():
        lst = list()
        lst.append('li')
        lst.extend(['st'])
        print(lst)


if __name__ == '__main__':
    ListAction.list_init()
    ListAction.list_index()
    ListAction.list_slicing()
    ListAction.list_repeat()
    ListAction.list_slicing_step()
    ListAction.list_in()
    ListAction.list_connect()
    ListAction.list_length()
    ListAction.to_list('HELLO')
    ListAction.list_to_string(lst=['1', '2'])
    ListAction.act()


对列表进行分段

In [1]: def te():
   ...:     a = [1,2,3,4,5,6,7,8,9]
   ...:     matrix = []
   ...:     for i in range(0,len(a),5):
   ...:         matrix.append(a[i:i+5])
   ...:     print(matrix)
   ...:

In [2]: te()
[[1, 2, 3, 4, 5], [6, 7, 8, 9]]


对两个列表的处理

可参考文档 https://blog.csdn.net/muumian123/article/details/81979084

求列表的差集-属于 A 列表,不属于 B 列表

方法一:
In [9]: def te():
   ...:     a = set([1,2,3])
   ...:     b = set([2,3,4])
   ...:     print(list(a-b))
   ...:

In [10]: te()
[1]


方法二:
In [11]: def te():
    ...:     a = [1,2,3]
    ...:     b = [2,3,0]
    ...:     for i in a:
    ...:         if i not in b:
    ...:             print(i)
    ...:

In [12]: te()
1

原文地址:https://www.cnblogs.com/hailongchen/p/10870601.html