当前位置:   article > 正文

python 实用小技巧_python max set

python max set

一、列表,元祖,集合、字典、字符串判空

在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")
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

二、交换变量

当我们要交换两个变量的值时,一种常规的方法是创建一个临时变量,然后用它来进行交换

a,b=1,2
a,b=b,a
print(a,b)
  • 1
  • 2
  • 3

三、将list中的所有元素转为单个字符串

使用join方法,自动将列表迭代出来进行字符串拼接

List=["python","is","interesting"]
print(" ".join(List))
  • 1
  • 2

四、查询列表中最多的元素

使用max方法,使用集合将列表去重

List=["1","2","1","3"]
print(max(set(List),key=List.count))
  • 1
  • 2

五、字符串倒转

python字符串切片法
a[头:尾:-1],-1是指从尾部倒着走,走一步
a[头:尾:2], 2指的是从头开始走,走两步

string="123456"
print(string[::-1])
  • 1
  • 2

六、字典get用法

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"))
  • 1
  • 2
  • 3
  • 4
  • 5

七、for … else语法

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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

八、两个列表合并

List=["1","2","3"]
List2=["4","5","6"]
print(List+List2)
  • 1
  • 2
  • 3

九、从list中删除重复项

把list转成set,去除重复项,再转回list

List=["1","2","3","1"]
print(list(set(List)))
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/357280
推荐阅读
相关标签
  

闽ICP备14008679号