Python列表(List)

添加值appendinsert

示例

list1 = ['google', 'baidu']
print(list1)
list1.append('souhu')
print(list1)
list1.insert(0, 'biying')
print(list1)

运行结果

['google', 'baidu']
['google', 'baidu', 'souhu']
['biying', 'google', 'baidu', 'souhu']

删除列表元素 popremove

示例

list1.remove('google')
print(list1)
list1.pop(-1)
print(list1)

运行结果

['biying', 'baidu', 'souhu']
['biying', 'baidu']

列表自定义排序

示例

import functools

class Node:
    def __init__(self, data, left, right):
        self.data = data
        self.left = left
        self.right = right

def node_cmp(node1, node2):
    """
    此函数用于存储节点的列表自定义排序
    node1,node2: Node类型的节点
    """
    if node1.data[1] > node2.data[1]:
        return 1
    elif node1.data[1] < node2.data[1]:
        return -1
    return 0

n1 = Node(('A', 10), None, None)
n2 = Node(('B', 5), None, None)
n3 = Node(('C', 3), None, None)
n4 = Node(('D', 7), None, None)
nodeList = [n1, n2, n3, n4]
for n in noteList:
    print(n.data)
print("-----------------------")
nodeList = sorted(nodeList, key=functools.cmp_to_key(node_cmp))
for n in noteList:
    print(n.data)

运行结果

('A', 10)
('B', 5)
('C', 3)
('D', 7)
-----------------------
('C', 3)
('B', 5)
('D', 7)
('A', 10)
Last modification:June 28th, 2020 at 11:14 am
如果觉得我的文章对你有用,请随意赞赏