首页 > 编程语言 > 详细

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

时间:2020-04-01 17:09:25      阅读:49      评论:0      收藏:0      [点我收藏+]
# 其他常用方法
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)
# 输出:[]

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

原文:https://www.cnblogs.com/ac-chang/p/12613658.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!