列表

 

序号

方法

1

list.append(obj)
在列表末尾添加新的对象

2

list.count(obj)
统计某个元素在列表中出现的次数

3

list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

4

list.index(obj)
从列表中找出某个值第一个匹配项的索引位置

5

list.insert(index, obj)
将对象插入列表

6

list.pop([index=-1]])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

7

list.remove(obj)
移除列表中某个值的第一个匹配项

8

list.reverse()
反向列表中元素

9

list.sort(cmp=None, key=None, reverse=False)
对原列表进行排序

10

list.clear()
清空列表

11

list.copy()
复制列表

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
列表操作
"""

# 连接操作:+
# a = [1]
# b = [2]
# c = a + b #[1, 2]
# print(c)


# 重复 *
# a = [1]
# c = a * 3  # [1, 1, 1]
# print(c)


# 索引
# a = [1, 2, 3]
# b = a[1] #2
# print(b)


# 切片
# a = [1, 2, 3]
# b = a[0:2]  # [ 1, 2]
# print(b)


# len() 长度
# a = [1, 2, 3]
# b = len(a)  # 3
# print(b)


# max() 最大值
# a = [1, 2, 3]
# b = max(a)  # 3
# print(b)

# min() 最小值
# a = [1, 2, 3]
# b = min(a)  # 1
# print(b)


# list()
# a = list((1, 2, 3))  # [1, 2, 3]
# print(a)


# 增加元素append(self, p_object)
# a = [1, 2, 3]
# b = 4
# a.append(b)  # [1, 2, 3, 4]
# print(a)


# 可以可迭代对象个每个元素添加到列表extend(self, iterable)
# a = [1, 2, 3]
# a.extend('abc')  # [1, 2, 3, 'a', 'b', 'c']
# print(a)


# 在指定索引增加元素insert(self, index, p_object)
# a = [1, 2, 3]
# a.insert(1, 5)  # [1, 5, 2, 3]
# print(a)


# 删除元素del()
# a = [1, 2, 3]
# del a[1]  # [1, 3]
# print(a)


# 删除指定索引的元素pop(self, index=None)
# a = [1, 2, 3, 4]
# b = a.pop()  # 4
# a.pop(5)# IndexError:pop index out of range
# print(a)  # [1, 2, 3]
# print(b)


# 删除指定值元素remove(self, value)
# a = [1, 2, 3, 4]
# a.remove(3)  # [1, 2, 4]
# a.remove(5)  # ValueError: list.remove(x): x not in list
# print(a)


# 清空所有元素clear(self)
# a = [1, 2, 3]
# a.clear()  # []
# print(a)


# 修改元素
# a = [1, 2, 3]
# a[1] = 5  # [1, 5, 3]
# print(a)


# 查找元素
# a = [1, 2, 3]
# b = 2 in a  # True
# b = 5 in a  # False
# print(b)


# 查找元素在列表中第一次出现的位置 index(self, value, start=None, stop=None)
# a = [1, 2, 3, 3,2, 3]
# index = a.index(2)  # 1
# index = a.index(2,2,5)  # 4
# index = a.index(5)  # ValueError: 5 is not in list
# print(index)


# 字符串转列表
# a = "abc"
# b = list(a)  # ['a', 'b', 'c']
# print(b)


# 出现次数count(self, value)
# a = "abcda"
# b = list(a)
# b = b.count("a")  # 2
# print(b)


# 浅复制copy(self)
# a = [1, 2, 3]
# b = a.copy()  # [1, 2, 3]
# print(b)


# 列表反转reverse(self)
# a = [1, 2, 3]
# a.reverse()  # [3, 2, 1]
# print(a)


# 利用切片反转列表
# a = [1, 2, 3]
# b = a[::-1]  # [3, 2, 1]
# print(b)


# 排序sort(self, key=None, reverse=False):
# a = [2, 1, 3]
# a.sort()  # [1, 2, 3]
# a.sort(reverse=True)  # [3, 2, 1]
# print(a)
View Code

 

字符串与列表相互转化 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    字符串与列表相互转换
"""

# 字符串根据某个分割符转换为列表  str.split(self, sep=None, maxsplit=-1)
# s = "Hello World!"
# print(s.split()) # ['Hello', 'World!']


#  列表转字符串 join()
# a = ['Hello', 'World!']
# b = " ".join(a)  # Hello World!
# print(b)
View Code

 

posted @ 2018-08-15 23:04  李小样  阅读(60)  评论(0编辑  收藏  举报