Python Basics points: types and operations

Source: Internet
Author: User
Tags readable readline set set

One: Type and Operation –1.1 seek help:
dir(obj)            # 简单的列出对象obj所包含的方法名称,返回一个字符串列表help(obj.func)      # 查询obj.func的具体介绍和用法
Three methods of –1.2 test type, recommend a third
if type(L) == type([]): print("L is list")if type(L) == list: print("L is list")if isinstance(L, list): print("L is list")
–1.3 python data type: hash type, non-hash type
# 哈希类型,即在原地不能改变的变量类型,不可变类型。可利用hash函数查看其hash值,也可以作为字典的key    "数字类型:int, float, decimal.Decimal, fractions.Fraction, complex"    "字符串类型:str, bytes"    "元组:tuple"    "冻结集合:frozenset"    "布尔类型:True, False"    "None"# 不可hash类型:原地可变类型:list、dict和set。它们不可以作为字典的key。
–1.4 Numeric Constants
1234, -1234, 0, 999999999                    # 整数1.23, 1., 3.14e-10, 4E210, 4.0e+210          # 浮点数0o177, 0x9ff, 0X9FF, 0b101010                # 八进制、十六进制、二进制数字3+4j, 3.0+4.0j, 3J                           # 复数常量,也可以用complex(real, image)来创建hex(I), oct(I), bin(I)                       # 将十进制数转化为十六进制、八进制、二进制表示的“字符串”int(str, base)                               # 将字符串转化为整数,base为进制数# 2.x中,有两种整数类型:一般整数(32位)和长整数(无穷精度)。可以用l或L结尾,迫使一般整数成为长整数float(‘inf‘), float(‘-inf‘), float(‘nan‘)    # 无穷大, 无穷小, 非数
Expression operators for –1.5 numbers
yield x                                      # 生成器函数发送协议lambda args: expression                      # 生成匿名函数x if y else z                                # 三元选择表达式x and y, x or y, not x                       # 逻辑与、逻辑或、逻辑非x in y, x not in y                           # 成员对象测试x is y, x is not y                           # 对象实体测试x<y, x<=y, x>y, x>=y, x==y, x!=y             # 大小比较,集合子集或超集值相等性操作符1 < a < 3                                    # Python中允许连续比较x|y, x&y, x^y                                # 位或、位与、位异或x<<y, x>>y                                   # 位操作:x左移、右移y位+, -, *, /, //, %, **                        # 真除法、floor除法:返回不大于真除法结果的整数值、取余、幂运算-x, +x, ~x                                   # 一元减法、识别、按位求补(取反)x[i], x[i:j:k], x(……)                        # 索引、分片、调用int(3.14),  float(3)                         # 强制类型转换
–1.6 integers can take advantage of the Bit_length function to test the number of digits
a = 1;       a.bit_length()    # 1a = 1024;    a.bit_length()    # 11
–1.7 the difference between repr and STR display formats
"""repr格式:默认的交互模式回显,产生的结果看起来它们就像是代码。str格式:打印语句,转化成一种对用户更加友好的格式。"""
–1.8 Digital-related modules
# math模块# Decimal模块:小数模块    import decimal    from decimal import Decimal    Decimal("0.01") + Decimal("0.02")        # 返回Decimal("0.03")    decimal.getcontext().prec = 4            # 设置全局精度为4 即小数点后边4位# Fraction模块:分数模块    from fractions import Fraction    x = Fraction(4, 6)                       # 分数类型 4/6    x = Fraction("0.25")                     # 分数类型 1/4 接收字符串类型的参数
–1.9 Set Set
"" Set is a set of unordered, non-repeating elements, with basic functionality including relationship testing and de-duplication elements. The set supports union (union), intersection (intersection), Difference (poor) and sysmmetric difference (symmetric difference sets) and other mathematical operations. Set supports X in Set, Len (set), and for X in set.  Set does not record element position or insertion point, so indexing, slicing, or other class sequence operation "" "s = Set ([3,5,9,10]) # Creates a collection of values, returns {3, 5, 9, 10}t = Set ("Hello") # Create a collection of unique characters return {}a = T | s t.union (s) # T and S of the set B = t & S t.intersection (s) # The intersection of T and S         c = T–s T.difference (s) # differential set (item in T, but not in s) d = t ^ s t.symmetric_difference (s)                                # symmetric difference set (items in t or S, but not both) T.add (' x ') t.remove (' H ') # Add/Remove an item t.update ([10,37,42]) # Use [...] Updates the S collection x in S, x not in S # set if there is a value s.issubset (t) s.issuperset (T) s.copy () S.discar D (x) S.clear () {x**2 for x in [1, 2, 3, 4]} # Set parsing, result: {, 1, 4, 9}{x for X in ' SpaM '} # Set parsing, result: {' A ', ' P ', ' s ', ' m '} 
–1.10 collection Frozenset, immutable objects
"""set是可变对象,即不存在hash值,不能作为字典的键值。同样的还有list、tuple等frozenset是不可变对象,即存在hash值,可作为字典的键值frozenset对象没有add、remove等方法,但有union/intersection/difference等方法"""a = set([1, 2, 3])b = set()b.add(a)                     # error: set是不可哈希类型b.add(frozenset(a))          # ok,将set变为frozenset,可哈希
–1.11 Boolean type bool
type(True)                   # 返回<class ‘bool‘>isinstance(False, int)       # bool类型属于整形,所以返回TrueTrue == 1, True is 1         # 输出(True, False)
–1.12 Dynamic Type Introduction
"""变量名通过引用,指向对象。Python中的“类型”属于对象,而不是变量,每个对象都包含有头部信息,比如"类型标示符" "引用计数器"等"""#共享引用及在原处修改:对于可变对象,要注意尽量不要共享引用!#共享引用和相等测试:    L = [1], M = [1], L is M            # 返回False    L = M = [1, 2, 3], L is M           # 返回True,共享引用#增强赋值和共享引用:普通+号会生成新的对象,而增强赋值+=会在原处修改    L = M = [1, 2]    L = L + [3, 4]                      # L = [1, 2, 3, 4], M = [1, 2]    L += [3, 4]                         # L = [1, 2, 3, 4], M = [1, 2, 3, 4
–1.13 common string constants and expressions
S = ‘‘                                  # 空字符串S = "spam’s"                            # 双引号和单引号相同S = "s\np\ta\x00m"                      # 转义字符S = """spam"""                          # 三重引号字符串,一般用于函数说明S = r‘\temp‘                            # Raw字符串,不会进行转义,抑制转义S = b‘Spam‘                             # Python3中的字节字符串S = u‘spam‘                             # Python2.6中的Unicode字符串s1+s2, s1*3, s[i], s[i:j], len(s)       # 字符串操作‘a %s parrot‘ % ‘kind‘                  # 字符串格式化表达式‘a {0} parrot‘.format(‘kind‘)           # 字符串格式化方法for x in s: print(x)                    # 字符串迭代,成员关系[x*2 for x in s]                        # 字符串列表解析‘,‘.join([‘a‘, ‘b‘, ‘c‘])               # 字符串输出,结果:a,b,c
–1.24 Dictionary Parsing
D = {k:8 for k in [‘s‘, ‘d‘]}                     # {‘d‘: 8, ‘s‘: 8}D = {k:v for (k, v) in zip([‘name‘, ‘age‘], [‘tom‘, 12])}
Special method for –1.25 dictionary __missing__: This method is executed when the lookup cannot find a key
class Dict(dict):    def __missing__(self, key):        self[key] = []        return self[key]dct = Dict()dct["foo"].append(1)    # 这有点类似于collections.defalutdictdct["foo"]              # [1]
– 1.26 The only difference between a tuple and a list is that tuples are immutable objects, and lists are mutable objects
a = [1, 2, 3]           # a[1] = 0, OKa = (1, 2, 3)           # a[1] = 0, Errora = ([1, 2])            # a[0][1] = 0, OKa = [(1, 2)]            # a[0][1] = 0, Error
– Special syntax for 1.27 tuples: commas and parentheses
D = (12)                # 此时D为一个整数 即D = 12D = (12, )              # 此时D为一个元组 即D = (12, )
–1.28 File Basic Operations
Output = open (R ' C:\spam ', ' W ') # Opens the file for input = open (' Data ', ' R ') # opens the file for reading.                     The open way can be ' W ', ' R ', ' A ', ' WB ', ' RB ', ' AB ' etc fp.read ([size]) # size for the length of the read, in bytes fp.readline ([size]) # read a line, if a size is defined, it is possible to return only a portion of a line fp.readlines ([size]) # Put the file each line as a member of a list and return the list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size parameter is supplied, the size is the total length of the read content. Fp.readable () # Whether readable fp.write (str) # writes STR to a file, write () does not add a newline character after Str. FP                              . Writelines (SEQ) # Writes the contents of the SEQ to the file (multiline write-once) fp.writeable () # is writable Fp.close () # Close the file.                             Fp.flush () # writes the contents of the buffer to the hard disk Fp.fileno () # Returns a long integer "File label" Fp.isatty () # file is a terminal device file (Unix system) Fp.tell () # Returns the current position of the file action tag, starting with the origin of the file fp.ne XT () # returns to the next line and shifts the file action marker to the next line. Use a file for the for ... inWhen a statement such as file is called, the next () function is invoked to implement the traversal. Fp.seek (Offset[,whence]) # Moves the file action marker to the location of offset. Whence can be calculated from scratch for 0, and 1 for the origin at the current position. 2 means that the end of the file is calculated as the origin. Fp.seekable () # can seekfp.truncate ([size]) # Cut the file to the specified size, and the default is the location of the current file action tag. For line in open (' data '): print (line) # using the For statement, the comparison applies to open larger files (' f.txt ', encoding = ' latin-1 ') # python3.x Unicode text File open (' F.bin ', ' RB ') # python3.x binary bytes File # File object also has corresponding properties: Buffer closed en Coding errors Line_buffering Name newlines etc.
–1.29 Other
# Python中的真假值含义:1. 数字如果非零,则为真,0为假。 2. 其他对象如果非空,则为真# 通常意义下的类型分类:1. 数字、序列、映射。 2. 可变类型和不可变类型

Python Basics points: types and operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.