当前位置 博文首页 > RunningOnMyWay的博客:Python3基础学习----数组列表list
>>> lis = [1,2,3]
>>> lis.append(4)
>>> lis
[1, 2, 3, 4]
insert(0,4) 第一个参数为数组索引位置,即在该位置插入元素
>>> lis.insert(0,4)
>>> lis
[4, 1, 2, 3]
新定义lis2,执行extend之后,lis2没有改变,而lis中多了lis2的元素
>>> lis2=["a","b"]
>>> lis.extend(lis2)
>>> lis
[4, 1, 2, 3, 'a', 'b']
>>> lis2
['a', 'b']
lis.pop()与lis.pop(-1)等效,0正数从左边开始,负数从右边开始索引位置
>>> lis.pop()
'b'
>>> lis
[4, 1, 2, 3, 'a']
>>> lis.pop(0)
4
>>> lis
[1, 2, 3, 'a']
>>>
在使用remove时默认只会删除第一个相同元素
>>> lis.append(2)
>>> lis
[1, 2, 3, 'a', 2]
>>> lis.remove(2)
>>> lis
[1, 3, 'a', 2]
>>>
使用clear方法清空了数组中的元素,而第二种新建了一个数组
>>> lis2.clear()
>>> lis2
[]
>>> lis2=["a","b"]
>>> lis2=[]
>>> lis2
[]
>>>
当元素不是同种类型时排序执行时会报错,使用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']
>>>
字符串转化为列表直接使用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'
>>> 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.
>>>
>>> dir(list)
['__add__', '__class__', '__contains__',..这里我手动省略..]
>>> dir(str)
['__add__', '__class__',..这里我手动省略..]
>>>