>  기사  >  백엔드 개발  >  Python3에서 목록 메소드를 구현하는 자세한 예

Python3에서 목록 메소드를 구현하는 자세한 예

黄舟
黄舟원래의
2017-10-09 10:38:091515검색

Python3 목록 시퀀스는 Python의 가장 기본적인 데이터 구조입니다. 다음 기사에서는 Python3 학습 노트의 목록 방법에 대한 관련 정보를 주로 소개합니다. 이 기사에서는 예제 코드를 통해 매우 자세하게 소개합니다. 공부나 일에 참고할 수 있는 학습가치, 도움이 필요한 친구들이 참고할 수 있습니다.

머리말

이 글은 주로 Python3 리스트 메소드에 대한 관련 내용을 소개하고 참고 및 학습을 위해 공유합니다. 아래에서는 자세한 소개를 살펴보겠습니다.

1 목록을 만들려면 [] 또는 list()를 사용하세요


user = []
user = list()

2 다른 유형을 목록으로 변환하려면 list()를 사용하세요


# 将字符串转成列表
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']

# 将元祖转成列表
>>> list(('a','b','c'))
['a', 'b', 'c']

3 [오프셋] 요소 가져오기 또는 요소 수정


>>> users = ['a','b','c','d','e']
# 可以使用整数来获取某个元素
>>> users[0]
'a'
# 可以使用负整数来表示从尾部获取某个元素
>>> users[-1]
'e'

# 数组越界会报错
>>> users[100]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> users[-100]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list index out of range

# 修改某个元素
>>> users[0] = &#39;wdd&#39;
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
>>>

4 목록 슬라이싱 및 요소 추출

목록을 슬라이싱하거나 추출한 후에도 여전히 목록입니다

다음과 같은 형식 : list [start:end:step]list[start:end:step]


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
# 正常截取 注意这里并不会截取到users[2]
>>> users[0:2]
[&#39;wdd&#39;, &#39;b&#39;]
# 也可从尾部截取
>>> users[0:-2]
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;]
# 这样可以获取所有的元素
>>> users[:]
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
# 也可以加上步长参数
>>> users[0:4:2]
[&#39;wdd&#39;, &#39;c&#39;]
# 也可以通过这种方式去将列表取反
>>> users[::-1]
[&#39;e&#39;, &#39;d&#39;, &#39;c&#39;, &#39;b&#39;, &#39;wdd&#39;]

# 注意切片时,偏移量可以越界,越界之后不会报错,仍然按照界限来处理 例如开始偏移量如果小于0,那么仍然会按照0去计算。
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
>>> users[-100:3]
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;]
>>> users[-100:100]
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
>>>

5 使用append()添加元素至尾部

形式如:list.append(item)


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;]
>>> users.append(&#39;ddw&#39;)
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;]

6 使用extend()或+=合并列表

形式如:list1.extend(list2)

这两个方法都会直接修改原列表


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;]
>>> names
[&#39;heihei&#39;, &#39;haha&#39;]
>>> users.extend(names)
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;]
>>> users += names
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;haha&#39;]

7 使用insert()在指定位置插入元素

形式如:list.insert(offset, item)

insert也不存在越界的问题,偏移量正负都行,越界之后会自动伸缩到界限之内,并不会报错


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;haha&#39;]
>>> users.insert(0,&#39;xiaoxiao&#39;)
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;haha&#39;]
>>> users.insert(-1,&#39;-xiaoxiao&#39;)
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
# 下面-100肯定越界了
>>> users.insert(-100,&#39;-xiaoxiao&#39;)
>>> users
[&#39;-xiaoxiao&#39;, &#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
# 下面100也是越界了
>>> users.insert(100,&#39;-xiaoxiao&#39;)
>>> users
[&#39;-xiaoxiao&#39;, &#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]

8 使用del删除某个元素

形式如:del list[offset]

del是python的语句,而不是列表的方法,del删除不存在的元素时,也会提示越界


>>> users
[&#39;-xiaoxiao&#39;, &#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]
>>> del users[0]
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]
>>> del users[100]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> del users[-100]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

9 使用remove删除具有指定值的元素

形式如:list.remove(value)


>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]
# 删除指定值&#39;c&#39;
>>> users.remove(&#39;c&#39;)
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]
# 删除不存在的值会报错
>>> users.remove(&#39;alsdkfjalsdf&#39;)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
# 如果该值存在多个,那么只能删除到第一个
>>> users.remove(&#39;haha&#39;)
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]

10 使用pop()方式返回某个元素后,并在数组里删除它

形式如:list.pop(offset=-1) 偏移量默认等于-1,也就是删除最后的元素


>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;, &#39;-xiaoxiao&#39;]
# 删除最后的元素
>>> users.pop()
&#39;-xiaoxiao&#39;
>>> users
[&#39;xiaoxiao&#39;, &#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
# 如果列表本身就是空的,那么pop时会报错
>>> user.pop(0)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: pop from empty list
>>> users.pop(0)
&#39;xiaoxiao&#39;
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
# 越界时也会报错
>>> users.pop(100)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: pop index out of range

11 使用index()查询具有特定值的元素位置

形式如:list.index(value)


# index只会返回第一遇到该值得位置
>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
>>> users.index(&#39;heihei&#39;)
5

# 如果该值不存在,也会报错
>>> users.index(&#39;laksdf&#39;)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: &#39;laksdf&#39; is not in list

12 使用in判断值是否存在列表

形式如:value in list


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
>>> &#39;wdd&#39; in users
True

13 使用count()记录特定值出现的次数

形式如:list.count(value)


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
>>> users.count(&#39;heihei&#39;)
2
>>> users.count(&#39;h&#39;)
0

14 使用join()将列表转为字符串

形式如:string.join(list)


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
>>> &#39;,&#39;.join(users)
&#39;wdd,b,d,e,ddw,heihei,heihei,-xiaoxiao,haha&#39;
>>> user
[]
>>> &#39;,&#39;.join(user)
&#39;&#39;

15 使用sort()重新排列列表元素

形式如:list.sort()


>>> users
[&#39;wdd&#39;, &#39;b&#39;, &#39;d&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;-xiaoxiao&#39;, &#39;haha&#39;]
# 默认是升序排序
>>> users.sort()
>>> users
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]
# 加入reverse=True, 可以降序排序
>>> users.sort(reverse=True)
>>> users
[&#39;wdd&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;d&#39;, &#39;b&#39;, &#39;-xiaoxiao&#39;]

# 通过匿名函数,传入函数进行自定义排序
>>> students
[{&#39;name&#39;: &#39;wdd&#39;, &#39;age&#39;: 343}, {&#39;name&#39;: &#39;ddw&#39;, &#39;age&#39;: 43}, {&#39;name&#39;: &#39;jik&#39;, &#39;age&#39;: 90}]
>>> students.sort(key=lambda item: item[&#39;age&#39;])
>>> students
[{&#39;name&#39;: &#39;ddw&#39;, &#39;age&#39;: 43}, {&#39;name&#39;: &#39;jik&#39;, &#39;age&#39;: 90}, {&#39;name&#39;: &#39;wdd&#39;, &#39;age&#39;: 343}]
>>> students.sort(key=lambda item: item[&#39;age&#39;], reverse=True)
>>> students
[{&#39;name&#39;: &#39;wdd&#39;, &#39;age&#39;: 343}, {&#39;name&#39;: &#39;jik&#39;, &#39;age&#39;: 90}, {&#39;name&#39;: &#39;ddw&#39;, &#39;age&#39;: 43}]
>>>

16 使用reverse()将列表翻转

形式如:list.reverse()


>>> users
[&#39;wdd&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;haha&#39;, &#39;e&#39;, &#39;ddw&#39;, &#39;d&#39;, &#39;b&#39;, &#39;-xiaoxiao&#39;]
>>> users.reverse()
>>> users
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]

17 使用copy()复制列表

形式如:list2 = list1.copy()

list2 = list1 这种并不是列表的复制,只是给列表起了别名。实际上还是指向同一个值。


>>> users
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]
>>> users2 = users.copy()
>>> users2
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]
>>>

18 使用clear()清空列表

形式如: list.clear()


>>> users2
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]
>>> users2.clear()
>>> users2
[]

19 使用len()获取列表长度

形式如:len(list)


>>> users
[&#39;-xiaoxiao&#39;, &#39;b&#39;, &#39;d&#39;, &#39;ddw&#39;, &#39;e&#39;, &#39;haha&#39;, &#39;heihei&#39;, &#39;heihei&#39;, &#39;wdd&#39;]
>>> len(users)
9

20 关于列表越界的深入思考

写了这些方法后,我有一些疑问,为什么有些操作会提示越界,有些则不会呢?

会提示偏移量越界的操作有

  • list[offset] 读取或者修改某个元素

  • del list[offset]

    🎜🎜rrreee🎜🎜🎜5 add()를 사용하여 끝에 요소를 추가하세요🎜🎜🎜🎜🎜형식은 다음과 같습니다: list.append( 항목)🎜 🎜🎜🎜rrreee🎜🎜🎜6 목록을 병합하려면 확장() 또는 +=를 사용하세요. 🎜🎜🎜🎜🎜다음과 같은 형식: list1.extend(list2)🎜🎜🎜 이 두 가지 메소드는 원본 목록을 직접 수정합니다 🎜🎜🎜🎜rrreee🎜🎜🎜7 insert()를 사용하여 지정된 위치에 요소를 삽입합니다. 🎜🎜🎜🎜🎜다음과 같은 형식: list.insert(offset, item) 🎜🎜🎜insert는 범위를 벗어나지 않습니다. 질문, 오프셋은 양수이거나 음수일 수 있습니다. 경계를 넘은 후 자동으로 경계 내로 크기가 조정되고 오류가 보고되지 않습니다.🎜🎜🎜🎜rrreee🎜🎜 🎜8 요소를 삭제하려면 del을 사용하세요🎜🎜🎜🎜🎜양식은 다음과 같습니다. del list[offset]🎜🎜🎜del은 목록 메서드가 아닌 Python 문입니다. 요소가 있으면 범위를 벗어났다는 메시지가 표시됩니다🎜🎜🎜🎜rrreee🎜🎜🎜9 제거를 사용하여 지정된 요소를 삭제합니다. 값 요소 🎜🎜🎜🎜🎜 형식은 list.remove(value)입니다. code>🎜🎜🎜🎜rrreee🎜🎜🎜10 요소를 반환하고 배열에서 삭제하려면 pop() 메서드를 사용하세요. 🎜🎜🎜🎜🎜양식은 다음과 같습니다: <code>list.pop(offset=-1) 오프셋은 기본적으로 -1이므로 마지막 요소가 삭제됩니다🎜🎜🎜🎜rrreee🎜🎜🎜11 인덱스( )를 사용하여 특정 값을 가진 요소의 위치를 ​​쿼리🎜🎜🎜🎜🎜양식 <code>list.index(value)🎜🎜🎜🎜rrreee🎜🎜🎜12 in을 사용하여 목록에 값이 있는지 확인하세요🎜🎜🎜🎜🎜 형식은 다음과 같습니다. value 목록에서🎜🎜🎜🎜rrreee🎜🎜🎜13 특정 값이 나타나는 횟수를 기록하려면 count()를 사용하세요🎜🎜🎜🎜🎜형식은 다음과 같습니다: list.count(value) / code>🎜🎜🎜🎜rrreee🎜🎜🎜14 Join()을 사용하여 목록을 문자열로 변환합니다🎜🎜🎜🎜🎜양식은 다음과 같습니다: <code>string.join(list)🎜🎜🎜🎜rrreee 🎜🎜 🎜15 목록 요소를 재정렬하려면 sort()를 사용하세요.🎜🎜🎜🎜🎜형식은 다음과 같습니다: list.sort()🎜🎜🎜🎜rrreee🎜🎜🎜16 목록을 뒤집으려면 reverse()를 사용하세요🎜 🎜🎜🎜 🎜형식: list.reverse()🎜🎜🎜🎜rrreee🎜🎜🎜17 목록을 복사하려면 copy()를 사용하세요🎜🎜🎜🎜🎜형식: list2 = list1 .copy()🎜🎜🎜<code>list2 = list1 이는 목록의 복사본이 아니며 목록에 별칭을 제공할 뿐입니다. 실제로는 여전히 동일한 값을 가리킵니다. 🎜🎜🎜🎜rrreee🎜🎜🎜18 목록을 지우려면 clear()를 사용하세요. 🎜🎜🎜🎜🎜형식은 다음과 같습니다: list.clear()🎜🎜🎜🎜rrreee🎜🎜🎜19 len() 사용 목록을 얻으려면 길이 🎜🎜🎜🎜🎜 형식은 다음과 같습니다. len(list)🎜🎜🎜🎜rrreee🎜🎜🎜20 목록 out-of-bounds🎜🎜🎜에 대한 심층적인 생각 🎜🎜이 메소드를 작성한 후 몇 가지 질문이 있습니다. 일부 작업은 범위를 벗어나는 메시지를 표시하는 반면 다른 작업은 메시지를 표시하지 않는 이유는 무엇입니까? 🎜🎜오프셋이 경계를 초과하도록 하는 작업에는 🎜
    • 🎜list[offset] 요소 읽기 또는 수정🎜이 포함됩니다. li >
    • 🎜del list[offset] 지정된 위치의 요소를 삭제합니다🎜
    • list.remove(value) 지정된 값의 요소 삭제 list.remove(value) 删除指定值的元素

    • list.pop(offset)

    list.pop(offset) 지정된 위치의 요소 삭제


    오프셋인 경우 금액이 한도를 초과하는 경우 이러한 메서드는 오류를 보고합니다. 내 개인적인 이해는 다음과 같습니다.

    오프셋 10이 있는 요소를 읽고 싶지만 요소가 존재하지 않는 경우 시스템이 오류 보고 없이 자동으로 목록의 마지막 요소를 읽는 경우 이는 불가능합니다. 허용되는 버그입니다. 10번째 요소를 삭제하고 싶은데 10번째 요소가 존재하지 않는데 시스템이 목록의 마지막 요소를 자동으로 삭제한다면 이는 참을 수 없는 일이라고 생각합니다.

    따라서 이러한 방법을 사용할 때는 오프셋에 있는 요소가 존재하는지 반드시 확인하세요. 그렇지 않으면 오류가 보고될 수 있습니다.

    요약🎜🎜🎜

위 내용은 Python3에서 목록 메소드를 구현하는 자세한 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.