列表元素的增加,删除,修改,查看

1.列表元素的增加

service = [‘http’, ‘ssh’, ‘ftp’]
1.直接添加元素
print(service + [‘firewalld’])

append:追加,追加一个元素到列表中

service.append(‘firewalld’)
print(service)

extend:拉伸,追加多个元素到列表中

service.extend([‘hello’,‘python’])
print(service)

insert:在索引位置插入元素

service.insert(0,‘firewalld’)
print(service)

列表的删除

service = [‘http’, ‘ssh’, ‘ftp’]

remove

service.remove(‘ftp’)
print(service)
service.remove(‘https’)
print(service)

claer:清空列表里面的所有元素

service.clear()
print(service)

del(python关键字) 从内存中删除列表(只能删除索引指定的元素)

del service[1]
print(service)

print(‘删除前两个元素之外的其他元素:’,end=’’)
del service[2:]
print(service)

弹出元素pop

弹出第一个元素:
service.pop(1)
print(service)

列表元素的修改

service = [‘ftp’,‘http’, ‘ssh’, ‘ftp’]

通过索引,重新赋值

将第一个元素改变
service[0] = ‘mysql’
print(service)

通过slice(切片)

将前两个元素进行改变
service[:2] = [‘mysql’,‘firewalld’]
print(service)

元素的查看

查看元素出现的次数

print(service.count(‘ftp’))

查看指定元素的索引值(也可以指定范围)

print(service.index(‘ssh’))
print(service.index(‘ssh’,4,8))

排序查看(按照ascii码进行由大到小排序)

print(service.sort(reverse=True))
print(service)

对字符串排序不区分大小写(按照由小到大排序)

phones = [‘alice’,‘bob’,‘harry’,‘Borry’]

phones.sort(key=str.lower)
phones.sort(key=str.upper)
print(phones)

猜你喜欢

转载自blog.csdn.net/qq_43279936/article/details/84558605