【Python基础入门】(13)List的常用方法

# 其他常用方法
persons = ["张三","赵六","李四","王五","赵六","钱七","孙八"]

1. list.count([指定元素]):返回指定元素出现的次数

# 获取指定元素出现次数
cnt = persons.count("赵六")
print(cnt) # 输出:2

2. list.extend([列表]):追加列表中元素

# 追加操作
# append是将整个列表追加至末尾,extend则是将列表中的元素追加到列表末尾
persons.append(["杨九","吴十"])
print(persons)
# 输出:['张三', '赵六', '李四', '王五', '赵六', '钱七', '孙八', ['杨九', '吴十']]
persons.extend(["杨九","吴十"])
print(persons)
# 输出:['张三', '赵六', '李四', '王五', '赵六', '钱七', '孙八', ['杨九', '吴十'], '杨九', '吴十']

3. in:判断元素是否存在

# in:用于判断数据在列表中是否存在,存在返回True,反之返回False
is_exist = "张三" in persons
print(is_exist) # 输出:True

4. list.copy():复制列表

# copy:用于复制表   注意:person1与person不是同一个对象
persons1 = persons.copy()
persons2 = persons
print(persons1)
is_same = persons1 is persons
print(is_same) # 输出:False
is_same = persons2 is persons
print(is_same) # 输出:True

5. list.clear():清空列表

# clear:清空列表
persons.clear()
print(persons)
# 输出:[]
print(persons1)
# 输出:['张三', '赵六', '李四', '王五', '赵六', '钱七', '孙八', ['杨九', '吴十'], '杨九', '吴十']
print(persons2)
# 输出:[]

猜你喜欢

转载自www.cnblogs.com/ac-chang/p/12613658.html