python list常用操作汇总

生成全0数组

n = 100
temp = [0 for _ in range(n)]

判断是否为空

temp = []
if temp: print('empty')
if not temp: print('not empty')

模拟栈

temp = []
temp.append(num) # 压入栈
temp.pop() # 弹出栈
temp[-1] # 取最后一个元素

模拟队列

temp = []
temp.append(num) # 加入队列
temp.pop(0) # 出队列
temp[0] # 队首元素

增加元素

temp = [0,1,2]
temp2 = [3,4,5]
num = 9
index = 2
temp.append(num) 
temp.insert(index, num) # num插入到下标2的位置
temp.extend(temp2) # 在之后连接上temp2

搜索

temp = [12,34,56]
ans = temp.index(34)

删除

temp = [12,34,56,34]
temp.remove(34) #删除第一个出现的34

元素连接成字符串

temp = [1,2,3,4,5,6]
s = ','.join(temp)

元素过滤

li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
[elem for elem in li if len(elem) > 1]
# ['mpilgrim', 'foo']

[elem for elem in li if elem != "b"]
# ['a', 'mpilgrim', 'foo', 'c', 'd', 'd']

[elem for elem in li if li.count(elem) == 1]
# ['a', 'mpilgrim', 'foo', 'c']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值