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()  # 换行
相关推荐
Julyyyyyyyyyyy41 分钟前
【软件测试】web自动化:Pycharm+Selenium+Firefox(一)
python·selenium·pycharm·自动化
Fanxt_Ja1 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
蓝婷儿1 小时前
6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
开发语言·python·学习
love530love2 小时前
【笔记】在 MSYS2(MINGW64)中正确安装 Rust
运维·开发语言·人工智能·windows·笔记·python·rust
水银嘻嘻2 小时前
05 APP 自动化- Appium 单点触控& 多点触控
python·appium·自动化
slandarer2 小时前
MATLAB | 绘图复刻(十九)| 轻松拿捏 Nature Communications 绘图
开发语言·matlab
狐凄2 小时前
Python实例题:Python计算二元二次方程组
开发语言·python
roman_日积跬步-终至千里3 小时前
【Go语言基础【3】】变量、常量、值类型与引用类型
开发语言·算法·golang
roman_日积跬步-终至千里3 小时前
【Go语言基础】基本语法
开发语言·golang·xcode
Felven3 小时前
C. Basketball Exercise
c语言·开发语言