您的位置:首页 > 编程语言 > Python开发

python使用汇总

2017-01-17 11:41 351 查看

python中函数参数*args和**kw的区别

*args是可变参数,args接收的是一个tuple,把list或tuple的元素变成可变参数传进去,即可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple(有序列表,元组,一旦初始化就不能修改):

**kw是关键字参数,kw接收的是一个dict。关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。

def person(name, age, **kw):
print 'name:', name, 'age:', age, 'other:', kw
person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}


zip 取所有输入数组的对应索引组成新的元组(tuple)列表

x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
## (1, 4), (2, 5), (3, 6)


linspace与arange 生成数组

x  = np.linspace(-8.0,8.0, 2000) ##开始,截止,个数
x  = np.arange(-8.0,8.0,1) ##开始 截止 步长


print {0} format

print("Epoch {0}: {1} / {2}".format(j, evaluate(test_data), n_test)) ##{索引} format 索引值


np.argmax返回数组最大值所在索引

np.argmax([20, 10])
## 0


join

语法: ‘sep’.join(seq)

参数说明

sep:分隔符。可以为空

seq:要连接的元素序列、字符串、元组、字典

返回值:返回一个以分隔符sep连接seq各个元素后生成的字符串

seq1 = ['hello','good','boy','doiido']
print ' '.join(seq1)
#hello good boy doiido
print ':'.join(seq1)
#hello:good:boy:doiido


os.path.join()合并路径

语法: os.path.join(path1[,path2[,……]])

import os
os.path.join('/hello/','good/boy/','doiido')
#'/hello/good/boy/doiido'


set集合运算 交 并 差 对称差集 子集 超集

1》交集
>>> x={1,2,3,4}
>>> y={3,4,5,6}
>>> x
set([1, 2, 3, 4])
>>> y
set([3, 4, 5, 6])
>>> x&y
set([3, 4])
>>> x.intersection(y)
set([3, 4])
2》并集
>>> x | y #集合并集
set([1, 2, 3, 4, 5, 6])
>>> x.union(y)
set([1, 2, 3, 4, 5, 6])
3》差集
>>> x-y # x与y的差集
set([1, 2])
>>> x.difference(y)# x与y的差集
set([1, 2])
>>> y-x # y与x的差集
set([5, 6])
>>> y.difference(x)# y与x的差集
set([5, 6])
4》对称差集
>>> x^y
set([1, 2, 5, 6])
>>> y^x
set([1, 2, 5, 6])
>>> x.symmetric_difference(y)
set([1, 2, 5, 6])
>>> y.symmetric_difference(x)
set([1, 2, 5, 6])
5》集合的子集和超集
>>> x
set([1, 2, 3, 4])
>>> z
set([1, 2, 3])
>>> z.issubset(x)#z是x的子集
True
>>> x.issuperset(z)#x是z的超集
True


按行写入文本

def list_to_file_bylines(path,list_data) :
file=open(path,'w')
for i in list_data:
file.write(i)
file.write("\n")
file.close()
print('ok')

list_to_file_bylines('../../data/dataset/feature/re_test.txt',re)


if判断

if expression :
suite
elif expression :
suite
else :
suite


while for循环

while 循环
while expression:
statement(s)
for 循环
for iterating_var in sequence:
statements(s)
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"


字符串截取

str = 'Hello World!'
print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 6th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string


字符串替换

##去空格
s.strip()
去空格及特殊符号
s.strip().lstrip().rstrip(',')
##大小写
sStr1 = sStr1.upper()
#sStr1 = sStr1.lower()
##替换
s.replace('www','ddd')


列表 生成与选择

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd to 4th
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists


元组 元组可以被认为是只读的列表

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')
print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd to 4th
print tuple[2:]       # Prints elements starting from 3rd element
print tinytuple * 2   # Prints list two times
print tuple + tinytuple # Prints concatenated lists


字典 由键值对组成

tinydict = {'name': 'john','code':6734, 'dept': 'sales',2: 'saxxs'}
print tinydict['name']  # Prints value for 'name' key
print tinydict[2]       # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values
john
saxxs
{'dept': 'sales', 2: 'saxxs', 'code': 6734, 'name': 'john'}
['dept', 2, 'code', 'name']
['sales', 'saxxs', 6734, 'john']


基本运算符

+ 加法 - 运算符的两侧的值增加
a + b = 30
- 减法- 从操作符左侧减去右手侧的值
a - b = -10
* 乘法- 相乘的运算符的两侧值
a * b = 200
/ 除法 - 由操作符的右侧的值除以左侧的值
b / a = 2
% 模- 由运算符的左侧除以运算符右侧返回余数
b % a = 0
** 指数幂- 执行运算符的指数(幂)计算
a**b = 10 的 20 次幂
// Floor Division - Floor除法 - 操作数相除,其结果的小数点后的数字将被删除。 9//2 = 4 , 9.0//2.0 = 4.0
== 检查两个操作数的值是否相等,如果是,则条件为真。
(a == b) 不为真 true.
!= 检查两个操作数的值相等与否,如果值不相等,则条件变为真。
(a != b) 为 true.
<> 检查两个操作数的值相等与否,如果值不相等,则条件变为真。
(a <> b) 为 true. 这个类似于 != 运算符
> 检查左边的操作数的值是否大于右操作数的值,如果是,则条件为真。
(a > b) 不为 true.
< 检查左边的操作数的值是否小于右操作数的值,如果是,则条件为真。
(a < b) 为 true.
>= 检查左边的操作数的值是否大于或等于右操作数的值,如果是,则条件为真。
(a >= b) 不为 true.
<= 检查左操作数的值是否小于或等于右操作数的值,如果是,则条件变为真。
(a <= b) 为 true.
= 简单的赋值运算符,从右侧的操作数赋值给左侧的操作数
c = a + b 将分配 a + b 的值到 c
+= 相加并赋值运算符,它增加了右操作数到左操作数并分配结果到左操作数
c += a 相当于 c = c + a
-= 相减并赋值运算符,它从左操作数减去右操作数并分配结果到左边操作数
c -= a 相当于 c = c - a
*= 乘法并赋值运算符,左操作数乘以右边的操作数并分配结果值到左操作数
c *= a 相当于 c = c * a
/= 除法并赋值运算符,左操作数除以右操作数并分配结果到左操作数
c /= a 相当于 c = c / a
%= 模量和赋值运算符,两个操作数模量并分配结果到左操作数
c %= a 相当于 c = c % a
**= 指数和赋值运算符,执行指数(次幂)计算的运算符并赋值给左操作数
c **= a 相当于 c = c ** a
//= Floor除法,并分配一个值,执行Floor除法运算并赋值给左操作数
c //= a 相当于 c = c // a
& 二进制和操作拷贝位结果,如果它存在于两个操作数。
(a & b) = 12 也就是 0000 1100
| 二进制或运算符复制位如果它存在一个操作数中。
(a | b) = 61 也就是 0011 1101
^ 二进制异或运算符复制,如果它设置在一个操作数,而不是两个比特。
(a ^ b) = 49  也就是 0011 0001
~ 二进制的补运算符是一元的,具有“翻转”位的效应。
(~a ) = -61 也就是 1100 0011 以2的补码形式,由于一个带符号二进制数。
<< 二进制向左移位运算符。左边的操作数的值向左移动由右操作数指定的位数。
a << 2 = 240 也就是 1111 0000
>> 二进制向右移位运算符。左边的操作数的值是通过右操作数指定向右移动的位数。
a >> 2 = 15 也就是 0000 1111
and 所谓逻辑和运算符。如果两个操作数为真,那么则条件为真。
(a 和 b) 为 true.
or 所谓逻辑OR运算符。如果任何两个操作数都非零那么条件变为真。
(a 或 b) 为 true.
not 所谓逻辑非运算符。用来反转其操作数的逻辑状态。如果条件为真,那么逻辑非操作符执行结果则为假。 not(a && b) 为 false.
in 计算结果为真,如果找到了变量指定的序列,否则为假。
x 在 y 中, 这里 in 结果是 1 ,如果 x is 是 y 序列成员
not in 如果变量没有在指定的顺序找到计算结果为真,否则为假。
x 不在 y 中, 这里 not in 结果是 1 ,如果 x 序列不是 y 的成员。
is 如果操作符两侧的变量是同一个对象计算结果为真,否则为假。
x 是 y, 这里 is 结果就是 1 ,如果 id(x) == id(y) 结果为 真.
is not 如果操作符两侧的变量为同一个对象,计算结果为假,否则真。
x 不是 y, 如果 id(x) 不为 id(y) 这里 is not 结果为 1


函数

def functionname( parameters ):
"function_docstring"   #可选的声明
function_suite
return [expression]


sys模块

sys模块的常见函数列表

sys.argv: 实现从程序外部向程序传递参数。

sys.exit([arg]): 程序中间的退出,arg=0为正常退出。

sys.getdefaultencoding(): 获取系统当前编码,一般默认为ascii。

sys.setdefaultencoding(): 设置系统默认编码,执行dir(sys)时不会看到这个方法,在解释器中执行不通过,可以先执行reload(sys),在执行 setdefaultencoding(‘utf8’),此时将系统默认编码设置为utf8。(见设置系统默认编码 )

sys.getfilesystemencoding(): 获取文件系统使用编码方式,Windows下返回’mbcs’,mac下返回’utf-8’.

sys.path: 获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。

sys.platform: 获取当前系统平台。

sys.stdin,sys.stdout,sys.stderr: stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们

sys.argv实现从程序外部向程序传递参数

sys.argv[0]表示代码本身文件路径

参数从1开始argv[1]

import sys
print sys.argv[0]
print sys.argv[1]


sys.path: 指定import路径

获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到

sys.path
sys.path.append("自定义模块路径/xx.py")
import xx


np.vstack行堆积 hstack 列堆积

行堆积

x = [3.0, 1.0, 0.2]
np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
np.hstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])


axis

axis=1 行运算

axis=0 列运算
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: