☞☞☞点击查看更多优秀Python博客☜☜☜
例如:删除数组a = [0,2,5,8,6,0,4,0]中的所有的0元素(当然元素也可以是字符串)可以使用一下代码进行:
a = [0,2,5,8,6,0,4,0]
b = filter(lambda x: x != 0, a)
print(list(b))
#结果如下[2,5,8,6,4]
例如今天我在写爬虫时爬取出来的一个元素特德前一个字符是我需要的,但是后面的字符我不想要,对于这种情况我采用了split()函数对其进行了分割,以下是代码:
str = "I LOVE HE YOU"
#加入我们想要提取I LOVE YOU
#可以采用以下代码
string = str.split() #可加入元素分割规则和分割次数默认为空格,分割无限次
print(string)
a = [0,2,5,8,6,0,4,0]
print(a[1:3])#[2, 5] 取第二个,第三个
print(a[1:])# [2,5,8,6,0,4,0]取第二个到最后
print(names[1:10])# [2,5,8,6,0,4,0] 超出数组长度后,返回剩余的全部
a = [0,2,5,8,6,0,4,0]
a.append("1")
print(a)#[0,2,5,8,6,0,4,0,1]
a = [0,2,5,8,6,0,4,0]
a.insert(1, "insert")
print(a)#[0,"insert",2,5,8,6,0,4,0]
names = ["alexl", "banana", "candna", "dell", "error"]
names[2] ="replaceItem"
print(names)#['alexl', 'insertItem', 'replaceItem', 'candna', 'dell', 'error', 'addddd']
names[3:5] = ["zurep", "zurep111"]
prnt(names)#['alexl', 'insertItem', 'replaceItem', 'zurep', 'zurep111', 'error', 'addddd']
names.remove("alexl")
print(names)#['insertItem', 'replaceItem', 'zurep', 'zurep111', 'error', 'addddd']
# names.remove(names[0])#也可以这样
# print(names)
a = [0,2,5,8,6,0,4,0]
b = a.pop(1)# 返回被删除的值
print(b)#2
print(a)#[0,2,5,8,6,0,4,0]
a = [0,2,5,8,6,0,4,0]
del a[0]
print(names)# [2,5,8,6,0,4,0]
b = [1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 55, 6, 6, 8]
print(b.count(1))#6
print(b.count(3))#10
print(b.count(5))#4
a = [1, 1, 1]
b = [3, 3, 3]
a.extend(b)
print(a)# [1, 1, 1, 3, 3, 3]
print(b)# [3, 3, 3]
以上就是今天在学习中遇到的问题,希望对你有所帮助。
学习来源:Python中数组的基本操作
零基础学Python教程