文档库 最新最全的文档下载
当前位置:文档库 › python函数中文手册

python函数中文手册

python函数中文手册
python函数中文手册

内置函数

一,文档说明

原始文档来自于python v2.7.2

中文译文和用法尚不完全,您可以自由修改和完善,

您可以在文档结尾鸣谢添上您的名字,我们将会感谢您做的贡献!

二,函数列表

1,取绝对值

abs(x)

Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

如果你不知道绝对值什么意思,那就要补一下小学数学了!

基本用法

2,

all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

3.

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

4.

basestring()

This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)).

是字符串和字符编码的超类,是抽象类型。不能被调用或者实例化。可以用来判断实例是否为字符串或者字符编码。

方法:

5.二进制转换

bin(x)

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

转换成二进制表达

方法:

6.布尔类型

bool([x])

Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True

布尔类型的转化

用法:

7. 二进制数组的转化

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding

(and optionally, errors) parameters; bytearray()

then converts the string to bytes using ().

If it is an integer, the array will have that size

and will be initialized with null bytes.

If it is an object conforming to the buffer interface,

a read-only buffer of the object will be used to

initialize the bytes array.

If it is an iterable, it must be an iterable of

integers in the range 0 <= x < 256, which are used

as the initial contents of the array.

Without an argument, an array of size 0 is created.

8.

callable(object)

Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__()method.

9.数字转化成字符

chr(i)

Return a string of one character whose ASCII code is the integer i. For example, chr(97) returns the string 'a'. This is the inverse of ord(). The argument must be in the range [0..255], inclusive; ValueError will be raised if i is outside that range. See also unichr().

用法:

10.

classmethod(function)

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

11.两两比较

cmp(x, y)

Compare the two objects x and y and return an integer

according to the outcome. The return value is negative if

x < y, zero if x == y and strictly positive if x > y.

X小于X输出负(-1),X等于Y输出零(0),X大于Y输出正(1)用法:

12.

compile(source, filename, mode[, flags[, dont_inherit]]) Compile the source into a code or AST object. Code objects can be executed by an exec statement or evaluated by a call to eval().

source can either be a string or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

13.

complex([real[, imag]])

Create a complex number with the value real+ imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long()and float(). If both arguments are omitted, returns 0j.

14.

delattr(object, name)

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided

the object allows it. For example, delattr(x, 'foobar') is equivalent to del .

15.字典

dict([arg])

Create a new data dictionary, optionally with items taken from arg. The dictionary type is described in Mapping Types — dict.

For other containers see the built in list, set, and tuple

classes, and the collections module.

16.很重要的函数,属性输出

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

方法

17.

divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a For floating point numbers the result is (q, a % b), where q is usually (a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a %

b) < abs(b).

18.

enumerate(sequence[, start=0])

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2])

19.

eval(expression[, globals[, locals]])

The arguments are a string and optional globals and locals.

If provided, globals must be a dictionary. If provided, locals can be any mapping object.

Changed in version : formerly locals was required to be

a dictionary.

20.

execfile(filename[, globals[, locals]])

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration —

PYTHON3中文教程

Python已经是3.1版本了,与时俱进更新教程. ?本文适合有Java编程经验的程序员快速熟悉Python ?本文程序在windows xp+python3.1a1测试通过. ?本文提到的idle指python shell,即安装python后你在菜单看到的IDLE(python gui) ?在idle里ctrl+n可以打开一个新窗口,输入源码后ctrl+s可以保存,f5运行程序. ?凡打开新窗口即指ctrl+n的操作. #打开新窗口,输入:#!/usr/bin/python #-*-coding:utf8-*-s1=input("Input your name:")print("你好,%s"%s1)''' 知识点: *input("某字符串")函数:显示"某字符串",并等待用户输入. *print()函数:如何打印. *如何应用中文 *如何用多行注释 ''' 2字符串和数字 但有趣的是,在javascript里我们会理想当然的将字符串和数字连接,因为是动态语言嘛.但在Python里有点诡异,如下: 运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换 #!/usr/bin/python #运行这行程序会出错,提示你字符串和数字不能连接,于是只好用内置函数进行转换a=2

b="test" c=str(a)+b d="1111" e=a+int(d)#How to print multiply values print("c is%s,e is%i"%(c,e))''' 知识点: *用int和str函数将字符串和数字进行转换 *打印以#开头,而不是习惯的// *打印多个参数的方式''' #!/usr/bin/python #-*-coding:utf8-*- #列表类似Javascript的数组,方便易用#定义元组word=['a','b','c','d','e','f','g']#如何通过索引访问元组里的元素a=word[2]print("a is:"+a) b=word[1:3]print("b is:")print(b)#index1and2elements of word.c=word[:2]print ("c is:")print(c)#index0and1elements of word.d=word[0:]print("d is:")print(d)# All elements of word.#元组可以合并e=word[:2]+word[2:]print("e is:")print(e)#All elements of word.f=word[-1]print("f is:")print(f)#The last elements of word.g=word[-4:-2]print("g is:")print(g)#index3and4elements of word.h=word[-2:]print("h is:")print(h)#The last two elements.i=word[:-2]print("i is: ")print(i)#Everything except the last two characters l=len(word)print("Length of word is:"+str(l))print("Adds new element") word.append('h')print(word)#删除元素del word[0]print(word)del word[1:3]print (word)''' 知识点: *列表长度是动态的,可任意添加删除元素. *用索引可以很方便访问元素,甚至返回一个子列表 *更多方法请参考Python的文档'''

python函数中文手册

内置函数 一,文档说明 原始文档来自于python v2.7.2 中文译文和用法尚不完全,您可以自由修改和完善, 您可以在文档结尾鸣谢添上您的名字,我们将会感谢您做的贡献! 二,函数列表 1,取绝对值 abs(x)

Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. 如果你不知道绝对值什么意思,那就要补一下小学数学了! 基本用法 2, all(iterable) Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to: 3. any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: 4. basestring() This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or unicode. isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)). 是字符串和字符编码的超类,是抽象类型。不能被调用或者实例化。可以用来判断实例是否为字符串或者字符编码。 方法: 5.二进制转换 bin(x) Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

Python常用内置函数总结

Python常用内置函数总结 一、数学相关 1、绝对值:abs(-1) 2、最大最小值:max([1,2,3])、min([1,2,3]) 3、序列长度:len('abc')、len([1,2,3])、len((1,2,3)) 4、取模:divmod(5,2)//(2,1) 5、乘方:pow(2,3,4)//2**3/4 6、浮点数:round(1)//1.0 二、功能相关 1、函数是否可调用:callable(funcname),注意,funcname变量要定义过 2、类型判断:isinstance(x,list/int) 3、比较:cmp('hello','hello') 4、快速生成序列:(x)range([start,] stop[, step]) 三、类型转换 1、int(x) 2、long(x) 3、float(x) 4、complex(x) //复数 5、str(x) 6、list(x) 7、tuple(x) //元组 8、hex(x) 9、oct(x) 10、chr(x)//返回x对应的字符,如chr(65)返回‘A' 11、ord(x)//返回字符对应的ASC码数字编号,如ord('A')返回65 四、字符串处理 1、首字母大写:str.capitalize 复制代码代码如下:

>>> 'hello'.capitalize() 'Hello' 2、字符串替换:str.replace 复制代码代码如下: >>> 'hello'.replace('l','2') 'he22o' 可以传三个参数,第三个参数为替换次数 3、字符串切割:str.split 复制代码代码如下: >>> 'hello'.split('l') ['he', '', 'o'] 可以传二个参数,第二个参数为切割次数 以上三个方法都可以引入String模块,然后用string.xxx的方式进行调用。 五、序列处理函数 1、len:序列长度 2、max:序列中最大值 3、min:最小值 4、filter:过滤序列 复制代码代码如下: >>> filter(lambda x:x%2==0, [1,2,3,4,5,6]) [2, 4, 6] 5、zip:并行遍历 复制代码代码如下:

python解释器内建函数帮助文档

Python解释器有很多内建函数。下面是以字母顺序列出 __import__( name[, globals[, locals[, fromlist[, level]]]]) 被import语句调用的函数。它的存在主要是为了你可以用另外一个有兼容接口的函数来改变import 语句的语义. 为什么和怎么做的例子, 标准库模块ihooks和rexec. 也可以查看imp, 它定义了有用的操作,你可以创建你自己的__import__()函数. 例如, 语句"import spam" 结果对应下面的调用: __import__('spam', globals(), locals(), [], -1); 语句"from spam.ham import eggs" 结果对应调用"__import__('spam.ham', globals(), locals(), ['eggs'], -1)". 注意即使locals()和['eggs']作为参数传递, __import__() 函数不会设置局部变量eggs; import语句后面的代码完成这项功能的. (实事上, 标准的执行根本没有使用局部参数, 仅仅使用globals决定import语句声明package的上下文.) 当name变量是package.module的形式, 正常讲, 将返回顶层包(第一个点左边的部分), 而不是名为name的模块. 然而, 当指定一个非空的formlist参数,将返回名为name的模块. 这样做是为了兼容为不同种类的import语句产生的字节码; 当使用"import spam.ham.eggs", 顶层包spam 必须在导入的空间中, 但是当使用"from spam.ham import eggs", 必须使用spam.ham子包来查找eggs变量. 作为这种行为的工作区间, 使用getattr()提取需要的组件. 例如, 你可以定义下面: def my_import(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod level指定了是否使用相对或绝对导入. 默认是-1将使用将尝试使用相对或绝对导入. 0 仅使用绝对导入.正数意味着相对查找模块文件夹的level层父文件夹中调用__import__。 abs( x) 返回一个数的绝对值。参数也许是一个普通或长整型,或者一个浮点数。如果参数是一个复数,返回它的积。 all( iterable) 如果迭代的所有元素都是真就返回真。 def all(iterable): for element in iterable: if not element: return False return True

Python3 常用函数

Python3 常用函数.笔记 Python 3自学.笔记 type()检查变量数据: >>> x = 10 >>> type(x) (cla ss ‘int’) exit( ) 执行到此命令时,程序终止:!!! >>> a = 0 >>> w hile a < 20: a = a + 1 if a == 5: else:#执行到此命令时,程序终止 a = 100 >>> print(a) 5 abs()返回一个数的绝对值: >>> abs(3) 3 >>> abs(-3) 3 while _ _ _ : 循环执行程序: >>> n = 0 >>> w hile n < 3:#(a n d/o r/n o t) n = n + 1 print(n) Continue 继续下一轮循环 Break 退出整个循环 round()对小数进行四舍五入操作: >>> x = 3.1415926 >>> round(x , 2) #保留2位小数

3.14 for _ _ _ in _ _ _ : 可以遍历任何序列的项目(如一个列表或者一个字符串): >>> s = 'a bc def123456' >>> for i in s: print(i) a b c d ...... range( ) 返回一个可迭代对象: >>> range(20) range(0, 20) #默认以0开始 >>> a = 20 >>> for i in ra nge(0 , a , 5): #步长为:5(默认步长为1)print(i) 5 10 15 #计数到20但不包括20 >>> break 退出整个循环: >>> i = 0 >>> w hile i < 10: i = i + 1 if i == 5: Break #执行到此时退出循环结构 >>> print(i) 5 字符串:

最新python常用函数资料

1.map()函数map()是Python 内置的高阶函数,它接收一个函数f和一个list,并通过把函数 f 依次作用在list 的每个元素上,得到一个新的list 并返回。 例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9] 如果希望把list的每个元素都作平方,就可以用map()函数: 因此,我们只需要传入函数f(x)=x*x,就可以利用map()函数完成这个计算: def f(x): return x*x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 输出结果: [1, 4, 9, 10, 25, 36, 49, 64, 81] 可以用列表替代 注意:map()函数不改变原有的list,而是返回一个新的list。

利用map()函数,可以把一个list 转换为另一个list,只需要传入转换函数。 由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的list,事实上它可以处理包含任意类型的list,只要传入的函数f可以处理这种数据类型。 假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list: 输入:['adam', 'LISA', 'barT'] 输出:['Adam', 'Lisa', 'Bart'] format_name(s)函数接收一个字符串,并且要返回格式化后的字符串,利用map()函数,就可以输出新的list。 参考代码: def format_name(s): return s[0].upper() + s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT']) 2.reduce()函数 reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和map()类似,一个函数f,一个list,但行为和map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list 的每个元素反复调用函数f,并返回最终结果值。 例如,编写一个f函数,接收x和y,返回x和y的和: def f(x, y): return x + y 调用reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:

PythonImagingLibrary中文手册p

这是P I L的官方手册,2005年5月6日本中文手册来你可以在PythonWare library找到改文档其它格式的版本以及先前的版本。 原版出处:htt 目录 1.Python Imaging Library 中文手册 2.第一部分:介绍 1.概览 1.介绍 2.图像归档处理 3.图像显示 4.图像处理 2.入门导引 1.使用Image 类 2.读写图像 3.裁剪、粘贴和合并图像 4.滚动一幅图像 5.分离与合并通道 3.几何变换 1.简单的几何变换 2.transpose图像 4.颜色变换 1.转换图像颜色模式 5.图像增强 1.滤波器 1.使用滤波器 2.点操作 1.使用点变换 2.处理单个通道 3.增强 1.增强图像 6.图像序列 1.读取图像序列 2.一个序列迭代类 7.Postscript格式打印 1.Drawing Postscript 8.更多关于读取图像 1.控制解码器 3.概念 1.通道 2.模式 3.大小 4.坐标系统

5.调色板 6.信息 7.滤波器 4.第二部分:模块手册 5.Image 模块 1.例子 2.函数 1.new 2.open 3.blend https://www.wendangku.net/doc/0712686639.html,posite 5.eval 6.frombuffer 7.fromstring 8.merge 3.方法 1.convert 2.copy 3.crop 4.draft 5.filter 6.fromstring 7.getbands 8.getbbox 9.getdata 10.getextrema 11.getpixel 12.histogram 13.load 14.offset 15.paste 16.point 17.putalpha 18.putdata 19.putpalette 20.putpixel 21.resize 22.rotate 23.save 24.seek 25.show 26.split 27.tell 28.thumbnail 29.tobitmap 30.tostring

Python常见数据结构整理

Python常见数据结构整理 2014年10月15日tenking阅读23 次 Python中常见的数据结构可以统称为容器(container)。序列(如列表和元组)、映射(如字典)以及集合(set)是三类主要的容器。 一、序列(列表、元组和字符串) 序列中的每个元素都有自己的编号。Python中有6种内建的序列。其中列表和元组是最常见的类型。其他包括字符串、Unicode字符串、buffer对象和xrange对象。下面重点介绍下列表、元组和字符串。 1、列表 列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能。 (1)、创建 通过下面的方式即可创建一个列表: 1 2 3 4list1=['hello','world'] print list1 list2=[1,2,3] print list2 输出: […hello?, …world?] [1, 2, 3] 可以看到,这中创建方式非常类似于javascript中的数组。(2)、list函数

通过list函数(其实list是一种类型而不是函数)对字符串创建列表非常有效: 1 2list3=list("hello") print list3 输出: […h?, …e?, …l?, …l?, …o?] 2、元组 元组与列表一样,也是一种序列,唯一不同的是元组不能被修改(字符串其实也有这种特点)。(1)、创建 1 2 3 4 5 6t1=1,2,3 t2="jeffreyzhao","cnblogs" t3=(1,2,3,4) t4=() t5=(1,) print t1,t2,t3,t4,t5 输出: (1, 2, 3) (…jeffreyzhao?, …cnblogs?) (1, 2, 3, 4) () (1,)从上面我们可以分析得出: a、逗号分隔一些值,元组自动创建完成; b、元组大部分时候是通过圆括号括起来的; c、空元组可以用没有包含内容的圆括号来表示; d、只含一个值的元组,必须加个逗号(,);(2)、tuple函数

python常用函数年初大总结

1.常用内置函数:(不用import就可以直接使用) help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像函数一样调用 repr(obj) 得到obj的表示字符串,可以利用这个字符串eval重建该对象的一个拷贝 eval_r(str) 表示合法的python表达式,返回这个表达式 dir(obj) 查看obj的name space中可见的name hasattr(obj,name) 查看一个obj的name space中是否有name getattr(obj,name) 得到一个obj的name space中的一个name setattr(obj,name,value) 为一个obj的name space中的一个name指向vale这个object delattr(obj,name) 从obj的name space中删除一个name vars(obj) 返回一个object的name space。用dictionary表示 locals() 返回一个局部name space,用dictionary表示 globals() 返回一个全局name space,用dictionary表示 type(obj) 查看一个obj的类型 isinstance(obj,cls) 查看obj是不是cls的instance issubclass(subcls,supcls) 查看subcls是不是supcls的子类 类型转换函数 chr(i) 把一个ASCII数值,变成字符 ord(i) 把一个字符或者unicode字符,变成ASCII数值 oct(x) 把整数x变成八进制表示的字符串 hex(x) 把整数x变成十六进制表示的字符串

Python 常用函数

Python 函数 2016年4月14日 22:07 1、join()函数 以下实例展示了join()的使用方法: #!/usr/bin/python str ="-"; seq =("a","b","c");# 字符串序列 print str.join( seq ); 以上实例输出结果如下: a-b-c 2、str.zfill(width) 将字符串str前面补0使得字符串长度为width 3、lambda函数(匿名函数) a. lambda表达式返回可调用的函数对象.但不会把这个函 数对象赋给一个标识符,而def则会把函数对象赋值给一个变 量. https://www.wendangku.net/doc/0712686639.html,mbda 它只是一个表达式,而def是一个语句 c.定义一些抽象的,不会别的地方再复用的函数 d. lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒 号右边的返回值 定义了一个lambda表达式,求三个数的和。 用lambda表达式求n的阶乘。 这里也可以把def直接写成lambda形式。如下 lambda函数可以很好和python中内建filter(),map(),reduce()函数的应用程序结合起来,因为它们都带了一个可执行的函数对象. 4、filter(function or None, sequence) -> list, tuple, or string 给定一个'过滤函数'和一个对象的序列,每个序列元素都通过这个过滤器进行筛选,保留函数返回为真的对象.filter函数为已知的序列的每个元素调用给定布尔函数.每个filter返回的非零(true)值元素添加到一个列表中. 1 2 3 #!/usr/bin/python2.5 from random import randint

python字符串内置函数

a='helLO' print(a.title()) # 首字母大写a='1 2'

执行结果:1 2 1 2 1 2 00000001 2 1 2 3 4 5 6 7 8 # 3 字符串搜索相关 .find() # 搜索指定字符串,没有返回-1 .index() # 同上,但是找不到会报错 .rfind() # 从右边开始查找 .count() # 统计指定的字符串出现的次数 # 上面所有方法都可以用index代替,不同的是使用index查找不到会抛异常,而find s='hello world' print(s.find('e')) # 搜索指定字符串,没有返回-1 print(s.find('w',1,2)) # 顾头不顾尾,找不到则返回-1不会报错,找到了 则显示索引 print(s.index('w',1,2)) # 同上,但是找不到会报错 print(s.count('o')) # 统计指定的字符串出现的次数 print(s.rfind('l')) # 从右边开始查找 # 4字符串替换 .replace('old','new') # 替换old为new .replace('old','new',次数) # 替换指定次数的old为new s='hello world' print(s.replace('world','python')) print(s.replace('l','p',2)) print(s.replace('l','p',5)) 执行结果: hello python heppo world heppo worpd

# 5字符串去空格及去指定字符 .strip() # 去两边空格 .lstrip() # 去左边空格 .rstrip() # 去右边空格 .split() # 默认按空格分隔 .split('指定字符') # 按指定字符分割字符串为数组 s=' h e-l lo ' print(s) print(s.strip()) print(s.lstrip()) print(s.rstrip()) print(s.split('-')) print(s.split()) # 6字符串判断相关 .startswith('start') # 是否以start开头 .endswith('end') # 是否以end结尾 .isalnum() # 是否全为字母或数字 .isalpha() # 是否全字母 .isdigit() # 是否全数字 .islower() # 是否全小写 .isupper() # 是否全大写 .istitle() # 判断首字母是否为大写 .isspace() # 判断字符是否为空格 # 补充 bin() # 十进制数转八进制 hex() # 十进制数转十六进制 range() # 函数:可以生成一个整数序列 type() # 查看数据类型 len() # 计算字符串长度 format() # 格式化字符串,类似%s,传递值能多不能少

python一些常用方法

1.list方法 一、创建一个列表 只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示: 与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。 二、访问列表中的值 使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示: print"list1[0]:",list1[0] print"list2[1:5]:",list2[1:5] 以上实例输出结果: 三、更新列表 你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示: list=['physics','chemistry',1997,2000]; print"Value available at index2:" print list[2]; list[2]=2001; print"New value available at index2:" print list[2];

以上实例输出结果: 四、删除列表元素 可以使用del语句来删除列表的的元素,如下实例: list1=['physics','chemistry',1997,2000]; print list1; del list1[2]; print"After deleting value at index2:" print list1; 以上实例输出结果: 五、Python列表脚本操作符 列表对+和*的操作符与字符串相似。+号用于组合列表,*号用于重复列表。如下所示: Python表达式结果描述 len([1,2,3])3长度 [1,2,3]+[4,5,6][1,2,3,4,5,6]组合 ['Hi!']*4['Hi!','Hi!','Hi!','Hi!']重复 3in[1,2,3]True元素是否存在于列表中 for x in[1,2,3]:print x,123迭代

python常用函数

1.map()函数 map()是Python 内置的高阶函数,它接收一个函数f和一个list,并通过把函数f 依次作用在li st 的每个元素上,得到一个新的list 并返回。 例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9] 如果希望把list的每个元素都作平方,就可以用map()函数: 因此,我们只需要传入函数f(x)=x*x,就可以利用map()函数完成这个计算: def f(x): return x*x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 输出结果: [1, 4, 9, 10, 25, 36, 49, 64, 81] 可以用列表替代 注意:map()函数不改变原有的list,而是返回一个新的list。

利用map()函数,可以把一个list 转换为另一个list,只需要传入转换函数。 由于list包含的元素可以是任何类型,因此,map() 不仅仅可以处理只包含数值的list,事实上它可以处理包含任意类型的list,只要传入的函数f可以处理这种数据类型。 假设用户输入的英文名字不规范,没有按照首字母大写,后续字母小写的规则,请利用map()函数,把一个list(包含若干不规范的英文名字)变成一个包含规范英文名字的list: 输入:['adam', 'LISA', 'barT'] 输出:['Adam', 'Lisa', 'Bart'] format_name(s)函数接收一个字符串,并且要返回格式化后的字符串,利用map()函数,就可以输出新的list。 参考代码: def format_name(s): return s[0].upper() + s[1:].lower() print map(format_name, ['adam', 'LISA', 'barT']) 2.reduce()函数 reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和map()类似,一个函数f,一个list,但行为和map()不同,reduce()传入的函数f 必须接收两个参数,reduce()对list 的每个元素反复调用函数f,并返回最终结果值。 例如,编写一个f函数,接收x和y,返回x和y的和: def f(x, y): return x + y 调用reduce(f, [1, 3, 5, 7, 9])时,reduce函数将做如下计算:

Python学习手册

Python学习手册 2014/01/16 第一部分:使用入门

1Python安装与测试 1.1下载地址 1.2安装注意 选择添加系统环境变量 1.3测试 Win+R>cmd>python 2如何运行程序 2.1基本语句 2**8表示2^8; Windows下可以使用Ctrl+Z来推出Python。 *对于数字来说,表示相乘,对于字符来说表示重复。不懂得话直接在交互模式下尝试。 交互提示模式也是一个测试程组件的地方:引入一个预编码的模块,测试里面的函数,获得当前工作目录的名称。 注意缩进(4个空格); 回车(Enter)两次,多行语句才会执行。 执行python,注意文件后缀为.py。

2.2UNIX可执行脚本(#!) 他们的第一行是特定的。脚本的第一行往往以字符#!开始(常叫做“hash bang”),其后紧跟着机器Python解释器的路径。 他们往往都拥有可执行的权限。Chmod+x 来修改可执行权限。 注意没有后缀名。Unix下运行命令为: % brain 运行结果: The Bright Side of Life… 2.3Unix env查找技巧 避免硬编码Python解释器的路径,env程序可以通过系统的搜索路径的设置定位Python解释器。这种方式比中的方法更常用。 2.4Windows下input的技巧 在windows系统下,双击后,会一闪而过,这时候就可以使用input()。一般来说input读取标准输入的下一行,如果还没有得到输入,就一直等待输入。从而达到了让脚本暂停的效果。 运行结果: 缺陷:看不到错误信息。 2.5模块导入和重载 每一个以扩展名py结尾的Python源代码文件都是一个模块。 其他模块可以通过导入这个模块读取这个模块的基础知识。 如上import可以运行,但只是在每次会话的第一次运行,在第一次导入之后,其他的导入都不会再工作。(这是有意设计的结果,导入是一个开销很大的操作) 2.6模块的显要特性:属性 作为替代方案,可以通过这样的语句从模块语句中获得变量名:

python字符串常用函数

字符串常用函数 replace(string,old,new[,maxsplit]) 字符串的替换函数,把字符串中的old替换成new。默认是把string中所有的old值替换成new 值,如果给出maxsplit值,还可控制替换的个数,如果maxsplit为1,则只替换第一个old 值。 >>>a="11223344" >>>print string.replace(a,"1","one") oneone2223344 >>>print string.replace(a,"1","one",1) one12223344 capitalize(string) 该函数可把字符串的首个字符替换成大字。 >>> import string >>> print string.capitalize("python") Python split(string,sep=None,maxsplit=-1) 从string字符串中返回一个列表,以sep的值为分界符。 >>> import string >>> ip="192.168.3.3" >>> ip_list=string.split(ip,'.') >>> print ip_list ['192', '168', '3', '3'] all( iterable) 如果迭代的所有元素都是真就返回真。 >>> l = [0,1,2,3] >>> all(l) Flase >>> l = [1,2,3] >>> all(l) True any( iterable) 如果迭代中有一个元素为真就返回真。 >>> l = [0,1,2,3] >>> all(l) True >>> l = [1,2,3] >>> all(l) True basestring() 这个抽象类型是str和unicode的父类。它不能被调用或初始化,但是它可以使用来测试一

python-ctypes模块中文帮助文档

内容: .加载动态链接库 .从已加载的dll中引用函数 .调用函数1 .基本的数据类型 .调用函数2 .用自己的数据类型调用函数 .确认需要的参数类型(函数原型) .返回值 .传递指针 .结构和联合 .结构或联合的对齐方式和字节的顺序 .结构和联合中的位 .数组 .指针 .类型转换 .未完成的类型 .回调函数 .访问dlls导出的值 .可变长度的数据类型 .bugs 将要做的和没有做的事情 注意:本文中的代码例子使用doctest确保他们能够实际工作。一些代码例子在linux和windows以及苹果机上执行有一定的差别 注意:一些代码引用了ctypes的c_int类型。它是c_long在32位机子上的别名,你不应该变得迷惑,如果你期望 的是c_int类型,实事上打印的是c_long,它们实事上是相同的类型。 加载动态链接库 ctypes加载动态链接库,导出cdll和在windows上同样也导出windll和oledll对象。 加载动态链接库后,你可以像使用对象的属性一样使用它们。cdll加载使用标准的cdecl调用约定的链接库, 而windll库使用stdcall调用约定,oledll也使用stdcall调用约定,同时确保函数返回一个windows HRESULT错误代码。这错误 代码自动的升为WindowsError Python exceptions,当这些函数调用失败时。 这有一些windows例子,msvcrt是微软的c标准库,包含大部分的标准c函数,同时使用cdecl调用约定。 注:cdecl和stdcall的区别请见https://www.wendangku.net/doc/0712686639.html,/log-20.html >>> from ctypes import * >>> print windll.kernel32 # doctest: +WINDOWS

Python内置的字符串处理函数整理字符串长度获取

Python内置的字符串处理函数整理字符串长度获取:len(str)例:print'%slengt By xuanfeng6666 at 2014-06-01 139 阅读 0 回复 0.0 希赛币 Python内置的字符串处理函数整理 ?字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) ?字母处理 全部大写:str.upper() 全部小写:str.lower() 大小写互换:str.swapcase() 首字母大写,其余小写:str.capitalize() 首字母大写:str.title() print '%s lower=%s' % (str,str.lower()) print '%s upper=%s' % (str,str.upper()) print '%s swapcase=%s' % (str,str.swapcase()) print '%s capitalize=%s' % (str,str.capitalize()) print '%s title=%s' % (str,str.title()) ?格式化相关 获取固定长度,右对齐,左边不够用空格补齐:str.rjust(width) 获取固定长度,左对齐,右边不够用空格补齐:str.ljust(width) 获取固定长度,中间对齐,两边不够用空格补齐:str.center(width) 获取固定长度,右对齐,左边不足用0补齐.zfill(width) print '%s ljust=%s' % (str,str.ljust(20))

python中常用的模块的总结

1、模块和包 a.定义: 模块用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本质就是.py 结尾的python文件。(例如:文件名:test.py,对应的模块名:test) 包:用来从逻辑上组织模块的,本质就是一个目录(必须带有一个__init__.py的文件)b.导入方法 import module_name import module_1的本质:是将module_1解释了一遍 也就是将module_1中的所有代码复制给了module_1 from module_name1 import name 本质是将module_name1中的name变量放到当前程序中运行一遍 所以调用的时候直接print(name)就可以打印出name变量的值 代码例子:自己写的模块,其他程序调用,如下所示: 模块module_1.py代码: 复制代码 1 name = "dean" 2 def say_hello(): 3 print("hello %s" %name) 调用模块的python程序main代码如下:(切记调用模块的时候只需要import模块名不需要加.py) import module_1 #调用变量 print(module_https://www.wendangku.net/doc/0712686639.html,)

#调用模块中的方法 module_1.say_hello() 复制代码 这样运行main程序后的结果如下: 1 D:\python35\python.exe D:/python培训/s14/day5/module_test/main.py 2 dean 3 hello dean 4 5 Process finished with exit code 0 import module_name1,module_name2 from module_name import *(这种方法不建议使用) from module_name import logger as log(别名的方法) c.导入模块的本质就是把python文件解释一遍 import module_name---->module_name.py---->module_name.py的路径---->sys.path 导入包的本质就是执行该包下面的__init__.py 关于导入包的一个代码例子: 新建一个package_test包,并在该包下面建立一个test1.py的python程序,在package包的同级目录建立一个p_test.py的程序 test1的代码如下: 1 def test(): 2 print("int the test1") package_test包下的__init__.py的代码如下: 1 #import test1 (理论上这样就可以但是在pycharm下测试必须用下面from .import test1) 2 from . import test1 3 print("in the init") p_test的代码如下: 1 import package_test #执行__init__.py 2 package_test.test1.test()

Wind量化平台-用户手册(Python)

——中国金融数据及工具首席服务商 9311509 Wind Python数据及交易接口 Version 1.1 修订时间:2014.02.12 上海万得信息技术股份有限公司 Shanghai Wind Information Co., Ltd. 地址上海浦东新区福山路33号建工大厦9楼 邮编Zip 200120 电话Tel (8621)6888 2280 传真Fax (8621)6888 2281 主页 https://www.wendangku.net/doc/0712686639.html,

版本历史

目录 1WINDPY接口说明 (1) 1.1W IND P Y接口概述 (1) 1.2W IND P Y接口安装 (2) 1.2.1WindPy对系统环境要求 (2) 1.2.2Python环境安装 (2) 1.2.3正常WindPy接口安装 (3) 1.2.4特殊安装WindPy方式 (6) 1.3接口向导界面 (6) 1.4W IND P Y获取帮助途径 (7) 1.4.1本用户手册 (7) 1.4.2量化交易群和R语言交流群 (7) 1.5W IND P Y接口相关规范 (1) 1.5.1以下所有命令都有如下假设 (1) 1.5.2命令区分大小写,且“w.”不能省略 (1) 1.5.3中文以及单字节码和双字节码的问题 (1) 1.5.4品种、指标、参数等引号内的部分不区分大小写 (1) 1.5.5参数支持list输入 (1) 1.5.6时间、日期支持Python语言的时间、日期格式 (2) 1.5.7参数中有缺省值的可以不用输入 (2) 1.5.8可以带参数名输入 (2)

1.5.9Showblank参数 (3) 1.5.10交易接口中Showfields参数 (3) 1.5.11ErrorCode定义 (3) 2WIND PY插件命令说明 (1) 2.1FROM W IND P Y IMPORT *:装载W IND P Y包 (1) 2.2W.START:启动W IND P Y (1) 2.3W.STOP:停止W IND P Y (2) 2.4W.ISCONNECTED:判断是否已经登录 (2) 2.5W.CANCEL R EQUEST:取消订阅 (2) 2.6W.WSD:获取历史序列数据 (3) 2.7W.WSI:获取分钟数据 (3) 2.8W.WST:获取日内TICK级别数据 (4) 2.9W.WSS:获历史截面数据 (5) 2.10W.WSQ:获取和订阅实时行情数据 (5) 2.11W.WSET:获取板块、指数等成分数据 (6) 2.12W.WEQS:获取条件选股结果 (7) 2.13W.WPF:获取资产管理、组合管理数据 (7) 2.14交易相关函数 (8) 2.14.1w.tlogon交易登录 (8) 2.14.2w.tlogout交易登出 (9) 2.14.3w.torder委托下单 (10) 2.14.4w.tcancel撤销委托 (11)

相关文档