首页 > 编程语言 >Python中你不知道的特性

Python中你不知道的特性

时间:2023-06-11 18:02:53浏览次数:40  
标签:10 set Python self 特性 call NewType 知道 first


无穷嵌套的列表

 

>>> a = [1, 2, 3, 4] 
>>> a.append(a) 
>>> a 
[1, 2, 3, 4, [...]] 
>>> a[4] 
[1, 2, 3, 4, [...]] 
>>> a[4][4][4][4][4][4][4][4][4][4] == a 
True

 

无穷嵌套的字典

>>> a = {} 
>>> b = {} 
>>> a['b'] = b 
>>> b['a'] = a 
>>> print a 
{'b': {'a': {...}}}

列表重构

>>> l = [[1, 2, 3], [4, 5], [6], [7, 8, 9]] 
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

或者

import itertools 
data = [[1, 2, 3], [4, 5, 6]] 
list(itertools.chain.from_iterable(data))

再或者

from functools import reduce
from operator import add
data = [[1, 2, 3], [4, 5, 6]]
reduce(add, data)

 

 

字典生成

>>> {a:a**2 for a in range(1, 10)}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

 

类中方法重置

class foo:
    def normal_call(self):
        print("normal_call")
    def call(self):
        print("first_call")
        self.call = self.normal_call

>>> y = foo()>>> y.call()
first_call
>>> y.call()
normal_call
>>> y.call()
normal_call
class GetAttr(object):
    def __getattribute__(self, name):
        f = lambda: "Hello {}".format(name)
        return f>>> g = GetAttr()
>>> g.Mark()
'Hello Mark'


>>> a = set([1,2,3,4])
>>> b = set([3,4,5,6])
>>> a | b # Combining{1, 2, 3, 4, 5, 6}
>>> a & b # Intersection{3, 4}
>>> a < b # SubsetsFalse>>> a - b # Variance{1, 2}
>>> a ^ b # The symmetric difference{1, 2, 5, 6}

集合定义必须使用set关键字, 除非使用集合生成器

{ x for x in range(10)} # Generator sets

set([1, 2, 3]) == {1, 2, 3}
set((i*2 for i in range(10))) == {i*2 for i in range(10)}

 

比较操作

>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20 
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True

 

动态创建新类

>>> NewType = type("NewType", (object,), {"x": "hello"})
>>> n = NewType()
>>> n.x'hello'

另一个普通版本

>>> class NewType(object):
>>>     x = "hello"
>>> n = NewType()
>>> n.x"hello"

条件赋值

x = 1 if (y == 10) else 2 
x = 3 if (y == 1) else 2 if (y == -1) else 1

 

变量解包

>>> first,second,*rest = (1,2,3,4,5,6,7,8)
>>> first # The first value1
>>> second # The second value2
>>> rest # All other values
[3, 4, 5, 6, 7, 8]
>>> first,*rest,last = (1,2,3,4,5,6,7,8)
>>> first1>>> rest
[2, 3, 4, 5, 6, 7]
>>> last8


>>> l = ["spam", "ham", "eggs"]
>>> list(enumerate(l)) 
>>> [(0, "spam"), (1, "ham"), (2, "eggs")]
>>> list(enumerate(l, 1)) # 指定计数起点
>>> [(1, "spam"), (2, "ham"), (3, "eggs")]

 

异常捕获中使用else

try: 
  function()
except Error:
  # If not load the try and declared Error
else:
  # If load the try and did not load except
finally:
  # Performed anyway

 

列表拷贝

 

错误的做法

>>> x = [1, 2, 3]
>>> y = x
>>> y[2] = 5>>> y
[1, 2, 5]
>>> x
[1, 2, 5]

 

正确的做法

>>> x = [1,2,3]
>>> y = x[:]
>>> y.pop()3>>> y
[1, 2]
>>> x
[1, 2, 3]

 

对于递归列表的做法

import copy
my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]} 
my_copy_dict = copy.deepcopy(my_dict)

 

英文原文: https://www.devbattles.com/en/sand/post-1799-Python_the_things_that_you_might_not_know

译者: 诗书塞外

标签:10,set,Python,self,特性,call,NewType,知道,first
From: https://blog.51cto.com/u_6186189/6458423

相关文章

  • Python | *args和**kwargs是什么?怎么用?
    在python语言写成的模块中的函数里,常常可以看到函数的参数表列里面有这两个参数,形如:defsome_function(*args,**kwargs):todolistreturn...*args和**kwargs是什么?首先,解释星号的作用,一个星号*的作用是将tuple或者list中的元素进行unpack,作为多个参数分开传入;两......
  • Python使用Redis实现一个简单作业调度系统
        概述Redis作为内存数据库的一个典型代表,已经在很多应用场景中被使用,这里仅就Redis的pub/sub功能来说说怎样通过此功能来实现一个简单的作业调度系统。这里只是想展现一个简单的想法,所以还是有很多需要考虑的东西没有包括在这个例子中,比如错误处理,持久化等。下面是实现上......
  • Python内存数据库/引擎(sqlite memlite pydblite)
        1初探在平时的开发工作中,我们可能会有这样的需求:我们希望有一个内存数据库或者数据引擎,用比较Pythonic的方式进行数据库的操作(比如说插入和查询)。举个具体的例子,分别向数据库db中插入两条数据,”a=1,b=1″和“a=1,b=2”,然后想查询a=1的数据可能会使用这样的语句db......
  • Python使用multiprocessing实现一个最简单的分布式作业调度系统
    介绍Python的multiprocessing模块不但支持多进程,其中managers子模块还支持把多进程分布到多台机器上。一个服务进程可以作为调度者,将任务分布到其他多个机器的多个进程中,依靠网络通信。想到这,就在想是不是可以使用此模块来实现一个简单的作业调度系统。实现Job首先创建一个Job类,为......
  • python flask 表单处理Flask-WTF
        涉及到的插件和包有Flask-WTF,WTForms。内容有表单的创建使用流程,一些最佳实践,还有在页面显示提示消息的简单方式,配合Flask内置的flash()。Flask的requset对象包含了client端发送过来的所有请求,在request.form中就有POST方法提交过来的表单数据。直接使用这些数据可以......
  • python调用浏览器,实现刷网页小程序
       python打开浏览器,可以做简单的刷网页的小程序and其他有想象力的程序。不过仅供学习,勿用非法用途。python的webbrowser模块支持对浏览器进行一些操作主要有以下三个方法:webbrowser.open(url,new=0,autoraise=True)webbrowser.open_new(url)webbrowser.open_n......
  • python中文乱码问题大总结
        在运行这样类似的代码:#!/usr/bin/envpythons="中文"prints最近经常遇到这样的问题:问题一:SyntaxError:Non-ASCIIcharacter'\xe4'infileE:\coding\python\Untitled6.pyonline3,butnoencodingdeclared;seehttp://www.python.org/peps/pep-0263.......
  • Python中http请求方法库汇总
    最近在使用python做接口测试,发现python中http请求方法有许多种,今天抽点时间把相关内容整理,分享给大家,具体内容如下所示:一、python自带库----urllib2python自带库urllib2使用的比较多,简单使用如下:importurllib2response=urllib2.urlopen('http://localhost:8080/jenkins/api/jso......
  • Python爬虫
    目录PythonSpider第一章爬虫入门1.1爬虫概述1.1.1爬虫原理1.1.2爬虫分类1.1.3爬虫应用1.2爬虫流程1.2.1爬取网页1.2.2解析网页1.2.3存储数据1.3爬虫协议1.3.1Robots协议1.3.2robots.txt文件简介1.3.3robots.txt文件详解1.3.4爬虫准则1.4爬虫环境1.4.1原生Python+......
  • 实验6 turtle绘图与python库应用编程体验
    task1_1代码:fromturtleimport*defmove(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n变形'''foriinrange(n):......