170104

列表的增删改

改:

smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

smart_phones[1] = 'nokia'

print(smart_phones)

增:

smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

smart_phones.append('nokia') #表示添加到末尾,而不影响其他元素

print(smart_phones)


smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

smart_phones.insert(1, 'nokia') #在指定位置插入新元素

print(smart_phones)

删:

1.使用del语句删除元素

smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

del smart_phones[1] #删除指定位置的元素

print(smart_phones)

注意:使用del删除元素后,无法再访问该元素

2.使用pop()删除元素

smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

popped_smart_phones = smart_phones.pop(2) #此处仅仅表达赋值,存储变量,括号中的数字表示删除的位置;没有数字表示删除最后一个元素

print(popped_smart_phones) #打印出来删除的元素

print(smart_phones) #打印出来删除指定元素后的列表

3.根据值删除元素:remove()

smart_phones = ['iphone', 'samsung', 'huawei', 'oppo', 'xiaomi']

print(smart_phones)

smart_phones.remove('samsung') #删除指定元素

print(smart_phones)

注意:remove()只删除第一个指定的值;如果删除的值在列表出现多次,要用到循环来判断

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容