python用法冷门技巧持续更新(20/10/21更新)

技巧一(20/6/10更新)

逆序获取list最后几个元素

>>a=list(range(10))
>>a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>n=3
>>a[:-n-1:-1]
[9, 8, 7]

技巧二(20/6/11更新)

比较符号可以连续使用

>>> 5>1>-4>-6
True
>>> 6<12>1<4
True
>>> 0>3<5
False

技巧三(20/7/17更新)

eval和repr 相反过程

>>> int('12')
12
>>> int('12') is eval('12')
True
>>> repr(12)
'12'
>>> repr(12) is str(12)
False
>>> repr(12) == str(12)
True

技巧四(20/7/17更新)

变量直接填在字符串内

>>> a=23
>>> f"this num is {a} !!!"
'this num is 23 !!!'

技巧五(20/8/1更新)

字典键键可以是元组,不能是list和set

>>> a={}
>>> a[(3,4)]=1
>>> a
{(3, 4): 1}

技巧六(20/9/2更新)

不要直接读(read()),不会出现内存错误

>>> with open(r"<文件路径>", 'r',encoding='utf8') as file:
		for line in file:
			print(line)
			
a
abc
dd

技巧七(20/9/9更新)

nonlocal 多重块时使用

def aa():
    c= 0
    def bb():
        nonlocal c
        c+= 10
        return count
    return bb

技巧八(20/9/9更新)

frozenset() 

技巧九(20/9/17更新)

能读本地也能读网上资源

>>> import smart_open
>>> f=smart_open.open("https://www.baidu.com")
>>> f.read()
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible........<这里省略>'
>>> f=smart_open.open(r"E:\Documents\test_data\vp_store\abstract\00.txt",encoding='utf8')
>>> f.read()
理论 研究 与 实践 应用

技巧十(20/10/21)

多级List浅复制问题再现,不要用乘式扩展

>>> a=[[]]*3
>>> b=[[],[],[]]
>>> c=[[] for i in range(3)]
>>> a
[[], [], []]
>>> b
[[], [], []]
>>> c
[[], [], []]
>>> a[0].append(1)
>>> b[0].append(1)
>>> c[0].append(1)
>>> a
[[1], [1], [1]]
>>> b
[[1], [], []]
>>> c
[[1], [], []]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值