Python列表2

python 复制代码
print("------------------------------ 列表的相关操作 ------------------------------------")
'''
lst.append('x')在列表lst最后增加一个元素
lst.insert(index,'x')在列表中第index位置增加一个元素
lst.clear()清除列表lst中所有元素
lst.pop(index)将列表lst中第index位置的元素取出,并从列表中将其删除
lst.remove('x')将列表lst中出现的第一个元素x删除
lst.reverse(x)将列表lst中的元素反转
lst.copy()拷贝列表lst中的所有元素,生成一个新的列表
'''
lst = ['hello','you','are','the','best','!']
print("原列表:",lst,id(lst))
lst.append('Good!')
print('在列表lst最后增加一个元素:',lst,id(lst))
lst.insert(3,'apple')
print('增加一个元素:',lst,id(lst))
lst.pop(5)
print('取出一个元素并删除',lst,id(lst))
print(lst.copy())
lst.reverse()
print(lst)


print("------------------------------ 列表的排序 ------------------------------------")
'''
(1)列表对象的sort方法
lst.sort(key = None,reverse = False)  # key表示排序规则,reverse表示排序方式,默认升序
(2)内置函数sorted()
sorted(iterable,key = None,reverse = False)  # iterable表示排序的对象
'''
a = [1,2,3,4,5]
print('a原列表:',a)
a.sort()
print('升序:',a)
a.sort(reverse=True)
print('降序:',a)
b = ['why','which','what','who']
print('b原列表:',b)
b.sort()
print('升序:',b)
b.sort(reverse=True)
print('降序:',b)
# 忽略大小写进行比较
b.sort(key = str.lower)  # 将每个元素转换为小写后再进行比较
print(b)
b.sort(key = str.upper)  # 将每个元素转换为大写后再进行比较
print(b)

c = [2,4,56,6,8]
print('c原列表:',c)
print("升序:",sorted(c))
c1 = sorted(c,reverse=True)
print("降序:",c1)
python 复制代码
print("------------------------------ 列表生成式 ------------------------------------")
import random
d = [item for item in range(1,11)]
print(d)
d = [item * item for item in range(1,11)]
print(d)
d = [random.randint(1,100) for _ in range(10)]
print(d)

print("------------------------------ 二维列表 ------------------------------------")
e = [
    ['城市','环比','同比'],
    ['北京','102','103'],
    ['上海','103','105'],
    ['深圳','100','104']
]
print(e)
for row in e:  # 行
    for item in row:  # 列
        print(item,end=" ")
    print()  # 换行
相关推荐
Python智慧行囊16 分钟前
前端三大件--HTML
css·python
大G哥39 分钟前
用 Go 和 TensorFlow 实现图像验证码识别系统
开发语言·后端·golang·tensorflow·neo4j
钢铁男儿1 小时前
深入解析C#参数传递:值参数 vs 引用参数
java·开发语言·c#
努力努力再努力wz1 小时前
【c++深入系列】:万字详解vector(附模拟实现的vector源码)
运维·开发语言·c++·c
.YM.Z1 小时前
C语言——操作符
c语言·开发语言·算法
yxc_inspire1 小时前
基于Qt的app开发第六天
开发语言·c++·qt
派阿喵搞电子1 小时前
yolov8中的python基础--模块导入篇
开发语言·python·pygame
qianqianaao1 小时前
实验六 基于Python的数字图像压缩算法
开发语言·图像处理·python·opencv·计算机视觉·自然语言处理·php
一点.点2 小时前
李沐动手深度学习(pycharm中运行笔记)——09.softmax回归+图像分类数据集+从零实现+简洁实现
pytorch·笔记·python·深度学习·动手深度学习·softmax回归
ElenaYu2 小时前
homebrew安装配置Python(MAC版)
开发语言·python·macos