赞
踩
在Python中,一个空列表,空元组,空字符串,空字典、None 的布尔值为False,具体如下所示
a=[] b=dict() c="" d=set() e=None if not a: print("empty a") if not b: print("empty b") if not c: print("empty c") if not d: print("empty set") if not e: print("is none")
当我们要交换两个变量的值时,一种常规的方法是创建一个临时变量,然后用它来进行交换
a,b=1,2
a,b=b,a
print(a,b)
使用join方法,自动将列表迭代出来进行字符串拼接
List=["python","is","interesting"]
print(" ".join(List))
使用max方法,使用集合将列表去重
List=["1","2","1","3"]
print(max(set(List),key=List.count))
python字符串切片法
a[头:尾:-1],-1是指从尾部倒着走,走一步
a[头:尾:2], 2指的是从头开始走,走两步
string="123456"
print(string[::-1])
1.当字典key不存在时,使用get获取value,默认返回None,可用于判断一个key是否在字典中
2.使用dict.get(key,“value“),有默认值返回默认值“value“
Dict={"a":"1","b":"2"}
#返回None
print(Dict.get("c"))
#返回默认值
print(Dict.get("c","value"))
for循环被break停止时,不运行else
List=["1","2","3"]
for i in List:
if i=="1":
break
else:
print("for循环被break停止时,不运行else")
for i in List:
if i=="5":
break
else:
print("当for循环break未停止时,运行else")
List=["1","2","3"]
List2=["4","5","6"]
print(List+List2)
把list转成set,去除重复项,再转回list
List=["1","2","3","1"]
print(list(set(List)))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。