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()  # 换行
相关推荐
李绍熹13 小时前
C语言基础语法示例
c语言·开发语言
kiki-bf13 小时前
使用python把图片转为word
开发语言·python·word
长安牧笛13 小时前
适老版线上超市,针对老年人的小程序,图片大,字大,主打日常用品+送货上门,还能电话下单,解决老年人不会用普通电商的问题。
python
@#---13 小时前
如何准确判断json文件并且拿到我想要的信息
android·python·json
光羽隹衡13 小时前
Python中的网络爬虫
开发语言·爬虫·python
Vantastic99913 小时前
基于Qwen Agent的多智能体协作系统:实现AI团队协同工作流
人工智能·python
不会写DN13 小时前
fmt 包中的所有 Print 系列函数
开发语言·后端·golang·go
zhongtianhulian13 小时前
陶瓷行业导航网站:景德镇信息大全 — 采购指南与政策解读
人工智能·python
南棱笑笑生14 小时前
20251213给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-6.1】系统时适配CTP触摸屏FT5X06
linux·c语言·开发语言·rockchip
电子_咸鱼14 小时前
常见面试题——滑动窗口算法
c++·后端·python·算法·leetcode·哈希算法·推荐算法