首页 / PYTHON / Python常用命令之集合
Python常用命令之集合
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python常用命令之集合,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2245字,纯文字阅读大概需要4分钟。
内容图文
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, ‘apple‘ is in the fruits list")
- 遍历list
thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)
获取list长度
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
追加元素
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
添加固定位置
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
删除某元素【只删除一个】
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
移除最后一个元素
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
清空List
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
修改元组值
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
声明元组
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple type is str
thistuple = ("apple")
合并元组Tuple 【不会去重】
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
构造元组【2个括号】
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
声明Set
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set添加元素
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
批量添加
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Set 删除元素
thisset = {"apple", "banana", "cherry"}
//不存在 抛异常
thisset.remove("banana")
//不存在 不抛异常
thisset.discard("banana")
// 不知道删的内容
x = thisset.pop()
print(thisset)
合并set 内容
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
合并set 内容(不需要新变量)
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
声明set
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Dictionary
创建字典
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
访问字段元素
# 如果没有值,异常
x = thisdict["mod1el"]
print(x)
# 如果没有值,返回None
x = thisdict.get("mo1del")
print(x)
输出字典的值
for x in thisdict.values():
print(x)
输出字典的k,v
for x, y in thisdict.items():
print(x, y)
复制 Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
原文:https://blog.51cto.com/dba10g/2488431
内容总结
以上是互联网集市为您收集整理的Python常用命令之集合全部内容,希望文章能够帮你解决Python常用命令之集合所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。