Python3基础学习----数组列表list

本文详细介绍了Python3中的列表操作,包括创建、尾部添加元素、插入元素、扩展列表、删除元素、清空数组、排序、字符串与列表的相互转化,以及如何查看方法帮助和对象方法。通过实例解析,帮助初学者掌握列表这一核心数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.列表创建
>>> lis = [1,2,3]
2.列表尾部添加元素
>>> lis.append(4)
>>> lis
[1, 2, 3, 4]
3.列表插入元素

insert(0,4) 第一个参数为数组索引位置,即在该位置插入元素

>>> lis.insert(0,4)
>>> lis
[4, 1, 2, 3]
4.扩展列表,可用于合并列表

新定义lis2,执行extend之后,lis2没有改变,而lis中多了lis2的元素

>>> lis2=["a","b"]
>>> lis.extend(lis2)
>>> lis
[4, 1, 2, 3, 'a', 'b']
>>> lis2
['a', 'b']
5.删除结尾或指定索引的元素

lis.pop()与lis.pop(-1)等效,0正数从左边开始,负数从右边开始索引位置

>>> lis.pop()
'b'
>>> lis
[4, 1, 2, 3, 'a']
>>> lis.pop(0)
4
>>> lis
[1, 2, 3, 'a']
>>> 
6.删除指定元素

在使用remove时默认只会删除第一个相同元素

>>> lis.append(2)
>>> lis
[1, 2, 3, 'a', 2]
>>> lis.remove(2)
>>> lis
[1, 3, 'a', 2]
>>> 
7.清空数组

使用clear方法清空了数组中的元素,而第二种新建了一个数组

>>> lis2.clear()
>>> lis2
[]
>>> lis2=["a","b"]
>>> lis2=[]
>>> lis2
[]
>>> 
8. 数组排序

当元素不是同种类型时排序执行时会报错,使用sort排序,使用reverse实现当前元素的反序; 使用sorted实现排序,会新生成一个数组,而不会改变原有数组;

>>> lis2=["b","c","a"]
>>> lis.sort()
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    lis.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> lis
[1, 3, 'a', 2]
>>> lis2.sort()
>>> lis2
['a', 'b', 'c']
>>> lis2.reverse()
>>> lis2
['c', 'b', 'a']
>>> sorted(lis2)
['a', 'b', 'c']
>>> lis2
['c', 'b', 'a']
>>> 
9.列表与字符串的互相转化

字符串转化为列表直接使用list方法,而将列表转为字符串时使用字符串的方法join,list是没有这个方法的;join之后返回一个字符串

>>> str1 = "abcdefd"
>>> str1
'abcdefd'
>>> lis2 = list(str1)
>>> lis2
['a', 'b', 'c', 'd', 'e', 'f', 'd']
>>> "".join(lis2)
'abcdefd'
>>> lis2
['a', 'b', 'c', 'd', 'e', 'f', 'd']
>>> "-".join(lis2)
'a-b-c-d-e-f-d'
>>> lis2.join("")
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    lis2.join("")
AttributeError: 'list' object has no attribute 'join'
10.查看方法的帮助文档
>>> help(str.join)
Help on method_descriptor:

join(self, iterable, /)
    Concatenate any number of strings.
    
    The string whose method is called is inserted in between each given string.
    The result is returned as a new string.
    
    Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

>>> help(list.append)
Help on method_descriptor:

append(self, object, /)
    Append object to the end of the list.

>>> 
11.查看当前对象有哪些方法
>>> dir(list)
['__add__', '__class__', '__contains__',..这里我手动省略..]
>>> dir(str)
['__add__', '__class__',..这里我手动省略..]
>>> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值