python随笔3月

1、用位运算实现两个数的交换

In [1]: x, y = 1, 2
In [2]: x, y = y, x # python 可以直接交换
In [3]: print('x={0},y={1}'.format(x,y))
out: x=2,y=1
In [4]: x = x ^ y # 利用位运算
In [5]: y = x ^ y
In [6]: x = x ^ y
In [7]: print('x={0},y={1}'.format(x,y))
out: x=1,y=2

2、inspect.signature()函数允许我们从一个可调用对象中提取出参数签名信息

In [1]: from inspect import signature
In [2]: def spam(x, y, z=42):
    ...:     pass
    ...: 
In [3]: sig = signature(spam)
In [4]: print(sig)
(x, y, z=42)
In [5]: sig.parameters
Out[5]: 
mappingproxy({'x': <Parameter "x">,
              'y': <Parameter "y">,
              'z': <Parameter "z=42">})
In [6]: sig.parameters['z'].name
Out[6]: 'z'
In [7]: sig.parameters['z'].default
Out[7]: 42
In [8]: sig.parameters['z'].kind
Out[8]: <_ParameterKind.POSITIONAL_OR_KEYWORD: 1>
In [9]: bound_types = sig.bind_partial(int, z=int)
#使用bind_partial()方法来对提供的类型到参数名做部分绑定
In [10]: bound_types
Out[10]: <BoundArguments (x=<class 'int'>, z=<class 'int'>)>
In [11]: bound_types.arguments
# 创建了有序字典
Out[11]: OrderedDict([('x', int), ('z', int)])
In [12]: bound_values = sig.bind(1,2,3)
# bind()做完全绑定
In [13]: bound_values.arguments
Out[13]: OrderedDict([('x', 1), ('y', 2), ('z', 3)])

3、二维数组去除重复元素

In [1]: a=[[],[1],[1,2],[1]]

In [2]: set(a) # 无法对数组里的数组使用set 需要先将其转化成tuple
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-3230717f5b63> in <module>()
----> 1 set(a)

TypeError: unhashable type: 'list'

In [3]: b=[list(j) for j in set([tuple(i) for i in a])]
In [4]: b
Out[4]: [[1, 2], [], [1]]

4、python中用户的多行输入

# 方法一:
import sys
list = []  
list_new = [] #定义一个空列表
for line in sys.stdin:    
#py.3中input()只能输入一行  sys.stdin按下换行键然后ctrl+d程序结束
    list_new = line.split()
    list.extend(list_new)#每一行组成的列表合并
print(list)

方法二:
sentinel = 'end' # 遇到这个就结束
lines = []
for line in iter(input, sentinel):
    lines.append(line)
# 或者:
from functools import partial

inputNew = partial(input,'Input something pls:\n')
sentinel = 'end' # 遇到这个就结束
lines = []
for line in iter(inputNew, sentinel):
    lines.append(line)

5、python中的partial函数

#函数在执行时,要带上所有必要的参数进行调用。但是,有时参数可以在函数被调用之前提前获知。这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。
[in] def add(a, b):
         return a + b
[in] add(2, 3)
[out] 5

[in] from functools import partial
[in] add_plus = partial(add,100)
[in] add_plus(10)
[out] 110
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值