Python中列表(List)的基本用法

一、列表的创建


list((3, 5, 7, 9, 11))
list(range(1, 10, 2))
""" 字符串、集合、字典的键、字典的键:值对转列表 """
list('hello, world')
list({3, 7, 8})
list({'a':3, 'b':9, 'c':78})
list({'a':3, 'b':9, 'c':78}.items())
""" 空列表 """
x = list()
x = []

二、列表的删除


del x

三、 列表元素访问及修改


x = list('python')
print(x)
""" 正数顺序访问,负数倒序访问 """
print(x[1])
print(x[-1])
""" 用下标进行修改 """
x[2] = 'a'
print(x)

四、 [增]操作:append()、insert()、extend()


x = [1, 2, 3]
""" append()尾部追加单个元素 """
x.append(4)
print(x)
""" insert()指定插入单个元素 """
x.insert(0, 0)
print(x)
""" extend()尾部追加列表 """
x.extend([5, 6, 7])
print(x)

五、[删]操作:pop()、remove()、clear()、del


x = [1, 2, 3, 4, 5, 6, 7]
""" pop()删除并返回指定位置元素(默认结尾处)(也可用负数来逆序弹出) """
print(x.pop())
print(x.pop(-2))
""" remove()删除首个指定的值,没有则抛出异常 """
x.remove(4)
print(x)
""" del 删除指定位置元素,后续元素会自动收缩 """
del x[2]
print(x)
""" clear()删除所有元素 """
x.clear()
print(x)

六、 [查]操作:下标、count()、index()


x = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
""" 下标查指定位置元素 """
print(x[4])
""" count()查指定元素出现次数 """
print(x.count(4))
""" index()查指定元素首次出现索引 """
print(x.index(3))

七、 排序操作:sort()、reverse()


x = list(range(11))
import random
""" 洗牌操作(打乱顺序) """
random.shuffle(x)
print(x)
""" sort()排序 """
""" 按字符串长度降序排序 """
x.sort(key=lambda item:len(str(item)), reverse=True)
print(x)
""" 按字符串大小升序排序:从左边开始第一个字符依次比较 """
x.sort(key=str)
print(x)
""" 默认排序(升序) """
x.sort()
print(x)
""" reverse()翻转 """
x.reverse()
print(x)

八、 复制:copy()浅复制、deepcopy()深复制


x = [1, 2, [3, 4]]
y = x.copy()
import copy
z = copy.deepcopy(x)

九、常见内置函数:max()、min()、sum()、len()、all()、any()、zip()、enumerate()


x = list(range(11))
""" all()检测是否所有元素等价于True """
print(all(x))
""" any()检测是否存在元素等价于True """
print(any(x))
""" 最大的数 """
print(max(x))
""" 最小的数 """
print(min(x))
""" 列表求和 """
print(sum(x))
""" 列表长度 """
print(len(x))
""" 多列表重组成元组 """
print(list(zip(x, [2]*11)))
""" 枚举列表元素 """
print(list(enumerate(x)))

十、对列表的+ 和 * 操作


""" + 操作(非原地操作-->返回新列表) """
x = [1, 2, 3]
print(id(x))
x = x + [4]
print(x)
print(id(x))
""" += 操作类似于append()原地操作 """
x += [5]
print(x)
print(id(x))

""" * 操作(非原地操作-->返回新列表) """
x = [1, 2, 3, 4]
print(id(x))
x = x * 2
print(x)
print(id(x))
x *= 2
print(x)
print(id(x))
""" 重复0次清空 """
x *= 0
print(x)

十一、列表推导式(列表解析式)


alist = [x * x for x in range(10)]
print(alist)
freshfruit = ['banana', ' loganberry', 'passion fruit']
alist = [w.strip() for w in freshfruit]
print(alist)
alist = list(map(lambda x : x.strip(), freshfruit))
print(alist)
alist = list(map(str.strip, freshfruit))
print(alist)
""" ①实现嵌套列表的平铺 """
vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
""" 第一个循环为外循环,第二个循环为内循环 """
print([num for elem in vec for num in elem])

print(list(chain(*vec)))

""" 过滤不符合条件的元素 """
alist = [-1, -4, 6, 7.5, -2.3, 9, -11]
print([i for i in alist if i > 0])

scores={"Zhang San":45, "Li Si":78, "Wang Wu":40, "Zhou Liu":96,
        "Zhao Qi":65, "Sun Ba":90, "Zheng Jiu":78, "Wu Shi":99,
        "Dong Shiyi":60}
highest = max(scores.values())
lowest = min(scores.values())
average = sum(scores.values())/len(scores)
print((highest, lowest, average))
highestPerson = [name for name, score in scores.items() if score == highest]
print(highestPerson)

from random import randint
x = [randint(1, 10) for i in range(20)]
print(x)
m = max(x)
print([index for index, value in enumerate(x) if value == m])

""" 同时遍历多个列表或可迭代对象 """
print([(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y])
print([(x, y) for x in [1, 2, 3] if x == 1 for y in [3, 1, 4] if y != x])

""" 使用列表解析式实现矩阵转置 """
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print([[row[i] for row in matrix] for i in range(4)])

print(list(map(list, zip(*matrix))))

""" 列表推导式中使用函数或复杂表达式 """
def f(v):
    if v % 2 == 0:
        v = v ** 2
    else:
        v = v + 1
    return v
print([f(v) for v in [2, 3, 4, -1] if v > 0])
print([v ** 2 if v % 2 == 0 else v + 1 for v in [2, 3, 4, -1] if v > 0])

""" 列表推导式生成100以内所有素数 """
print([p for p in range(2, 100) if 0 not in [p % d for d in range(2, int(sqrt(p)) + 1)]])

推荐阅读更多精彩内容