对于Python,一切事物都是对象,对象基于类创建
不同类型的类可以创造出字符串,数字,列表这样的对象,比如"koka"、24、[‘北京‘, ‘上海‘, ‘深圳‘]
数据类型(补python学习笔记一)
1、如何查找数据类型支持的方法
在python3.5终端中:
name=”koka“ type(name) <class ‘str‘>
help(name) #即可显示所有字符串支持的方法
或者
dir(name) #也可以显示对象中的所有特性。
使用Pycharm:
在py文件中输入int或str,选中输入的关键字,按住Ctrl等鼠标变成手指标识,左键单击即可到你想查找的类方法介绍
比如 int
class int(object): """ int(x=0) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100‘, base=0) 4 """ def bit_length(self): # real signature unknown; restored from __doc__ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) ‘0b100101‘ >>> (37).bit_length() 6 """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any int. """ pass @classmethod # known case def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ int.from_bytes(bytes, byteorder, *, signed=False) -> int Return the integer represented by the given array of bytes. The bytes argument must be a bytes-like object (e.g. bytes or bytearray). The byteorder argument determines the byte order used to represent the integer. If byteorder is ‘big‘, the most significant byte is at the beginning of the byte array. If byteorder is ‘little‘, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder‘ as the byte order value. The signed keyword-only argument indicates whether two‘s complement is used to represent the integer. """ pass def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__ """ int.to_bytes(length, byteorder, *, signed=False) -> bytes Return an array of bytes representing an integer. The integer is represented using length bytes. An OverflowError is raised if the integer is not representable with the given number of bytes. The byteorder argument determines the byte order used to represent the integer. If byteorder is ‘big‘, the most significant byte is at the beginning of the byte array. If byteorder is ‘little‘, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder‘ as the byte order value. The signed keyword-only argument determines whether two‘s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised. """ pass def __abs__(self, *args, **kwargs): # real signature unknown """ abs(self) """ pass def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __bool__(self, *args, **kwargs): # real signature unknown """ self != 0 """ pass def __ceil__(self, *args, **kwargs): # real signature unknown """ Ceiling of an Integral returns itself. """ pass def __divmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(self, value). """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __float__(self, *args, **kwargs): # real signature unknown """ float(self) """ pass def __floordiv__(self, *args, **kwargs): # real signature unknown """ Return self//value. """ pass def __floor__(self, *args, **kwargs): # real signature unknown """ Flooring an Integral returns itself. """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __index__(self, *args, **kwargs): # real signature unknown """ Return self converted to an integer, if self is suitable for use as an index into a list. """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ int(x=0) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100‘, base=0) 4 # (copied from class doc) """ pass def __int__(self, *args, **kwargs): # real signature unknown """ int(self) """ pass def __invert__(self, *args, **kwargs): # real signature unknown """ ~self """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lshift__(self, *args, **kwargs): # real signature unknown """ Return self<<value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __neg__(self, *args, **kwargs): # real signature unknown """ -self """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __pos__(self, *args, **kwargs): # real signature unknown """ +self """ pass def __pow__(self, *args, **kwargs): # real signature unknown """ Return pow(self, value, mod). """ pass def __radd__(self, *args, **kwargs): # real signature unknown """ Return value+self. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __rdivmod__(self, *args, **kwargs): # real signature unknown """ Return divmod(value, self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rfloordiv__(self, *args, **kwargs): # real signature unknown """ Return value//self. """ pass def __rlshift__(self, *args, **kwargs): # real signature unknown """ Return value<<self. """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return value*self. """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __round__(self, *args, **kwargs): # real signature unknown """ Rounding an Integral returns itself. Rounding with an ndigits argument also returns an integer. """ pass def __rpow__(self, *args, **kwargs): # real signature unknown """ Return pow(value, self, mod). """ pass def __rrshift__(self, *args, **kwargs): # real signature unknown """ Return value>>self. """ pass def __rshift__(self, *args, **kwargs): # real signature unknown """ Return self>>value. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rtruediv__(self, *args, **kwargs): # real signature unknown """ Return value/self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __truediv__(self, *args, **kwargs): # real signature unknown """ Return self/value. """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number"""
选中int后按如下操作可以在pycharm的左侧显示int(object)的方法,方便查看
整数
加法:x.__add__(y) <==> x+y
>>> x=3 >>> y=5 >>> x.__add__(y) 8 >>> x+y 8
abs : 求绝对值,x.__abs__() <==> abs(x)
>>> x=-3 >>> abs(x) 3 >>> x.__abs__() 3
divmod:相除,得到商和余数组成的元组 x.__divmod__(y) <==> divmod(x, y) #在网页分页操作中使用。
>>> total = 95 >>> pager = 10 >>> total.__divmod__(pager) (9, 5)
>>> divmod(total,pager)
(9, 5)
字符串
capitalize 首字母变大写
>>> name = "python" >>> name.capitalize() ‘Python‘
in or __contain__ 包含
>>> name = "python" >>> name.capitalize() ‘Python‘ >>> name.__contains__(‘th‘) True
startswith 和 endswith 以xx开头或xx结尾
>>> name = "Gumby" >>> name.endswith(‘Gumby‘) True >>> name = "Mr.Gumby" >>> name.startswith(‘Mr.‘) True
ljust,center,rjust 左对齐,居中,右对齐
>>> print(‘‘.ljust(35,‘=‘))
===================================
>>> print("Shopping List:".center(35,"*"))
***********Shopping List:**********
>>> print(‘‘.rjust(35,‘=‘))
===================================
count 统计字符出现次数
>>> abc = ‘asdadqweqjkhwjgfawgdklawda‘ >>> abc.count(‘a‘) 5 >>> abc.count(‘a‘,0,5) 2
encode 编码
>>> name = "下载" >>> result = name.encode(‘gbk‘) >>> print(result) b‘\xcf\xc2\xd4\xd8‘
列表(参考python学习笔记一)
元组
元组不可以改变,元组下的元素是可以改变的。
>>> tu.remove(11)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
tu.remove(11)
AttributeError: ‘tuple‘ object has no attribute ‘remove‘
>>>
>>> tu = (11,[22,33],"haha",44) >>> tu[1][0]=11 >>> tu (11, [11, 33], ‘haha‘, 44)
count 统计出现次数
>>> tu = (11,22,33,44) >>> tu.count(11) 1
index 查找元素出现的位置
>>> tu.index(22) 1 >>> tu.index(33) 2
字典
copy 返回一个具有相同键值对的新字典(这个方法实现的是浅复制,因为值本身就是相同,而不是副本。)
>>> x ={‘username‘:‘koka‘,‘sx‘:[‘it‘,‘js‘,12345]} >>> y = x.copy() >>> y[‘username‘] = ‘akok‘ >>> y[‘sx‘].remove(‘it‘) >>> y {‘username‘: ‘akok‘, ‘sx‘: [‘js‘, 12345]} >>> x {‘username‘: ‘koka‘, ‘sx‘: [‘js‘, 12345]}
练习:元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {‘k1‘: 大于66 , ‘k2‘: 小于66}
a = [11,22,33,44,55,66,77,88,99] b = {} for item in a: if item >= 66: if ‘k1‘ in b: b[‘k1‘].append(item) else: b[‘k1‘] = [item,] else: if ‘k2‘ in b: b[‘k2‘].append(item) else: b[‘k2‘] = [item,] print(b) """ for i in a: if i >=66: b.setdefault(‘k1‘,[]).append(i) else: b.setdefault(‘k2‘,[]).append(i) print(b) """
"""
import collections
values = [11, 22, 33,44,55,66,77,88,99]
newvalues = collections.defaultdict(list)
for i in values:
if i >= 66:
newvalues[‘k1‘].append(i)
else:
newvalues[‘k2‘].append(i)
print(newvalues)
"""
原文:http://www.cnblogs.com/koka24/p/5118443.html