Introduction to Python data types

Source: Internet
Author: User
Tags shallow copy sin square root

Ipython: Native python does not have command-line complement, this tool provides shell-like functionality to facilitate learning using
Installation:
wget https://repo.continuum.io/archive/Anaconda2-5.1.0-Linux-x86_64.sh #利用这个工具来管理python版本
SH anaconda2-5.1.0-linux-x86_64.sh
Conda Search Python
Conda create-n py27 python=2.7 Anaconda #创建2.7 environment

1. "All Objects"

例子1:In [3]: name=‘jerry‘In [4]: id(name)Out[4]: 140621392396080In [6]: name=‘tom‘In [7]: id(name)Out[7]: 140621403686472name=‘jerry‘,为了方便理解可以看成name的值是‘jerry‘,但是当我们对name重新赋值的时候,并不是改变jerry这个值,而是新建一个值‘tom‘,再把name重新指向到tom,所以两次name的id不一样,‘jerry‘和‘tom‘这种值在python中不叫值,而是被认为是一个对象python的核心概念就是‘一切皆对象‘,根据值的可变与否可以分为可变和不可变对象,我个人是这么理解的:    "可变对象都是对不可变对象的引用集合,改变可变对象的值的时候,对象/值本身不改变,而是引用改变了"例子2:In [107]: l1="hehe"In [108]: l2=[l1,"66"]In [109]: print l2[‘hehe‘, ‘66‘]In [110]: l1="haha"In [111]: print l2[‘hehe‘, ‘66‘]In [112]: id(l1)Out[112]: 139910507684560In [113]: l3="haha"In [114]: id(l3)Out[114]: 139910507684560In [115]: l2=["haha","xxx"]In [116]: id(l2[0])Out[116]: 139910507684560从这个例子可以看出:    l2[0]引用的是l1的数据对象部分,当对l1重新赋值的时候,并不影响l2的值    l1、l3和l2[0],引用的都是同一数据对象,所以id都相同从上面就不难理解:‘python的变量没有类型,数据才有类型‘这句话,因为变量只是个引用,类似于c语言中的指针

Properties and methods of the 2.python class
Reference: http://python.jobbole.com/82297/(written in very detailed, recommended to see)

类:python的类也是一种对象,它类似于一种框架,当我们需要用到它的时候就对它进行实例化,比如:    name=‘jerry‘,name可以看做字符类型str()的一个实例属性:数据,可以用" 类的实例.属性名 "引用方法:操作,可以用" 类的实例.方法名()"引用属性与方法的区别在于,属性引用的是数据,而方法引用的是一段代码,属性是在类实例化过程中进行赋值的,而方法则类定义时就已经写好,所以,当某个变量属于某个类时,它能使用的方法/操作也就确定了

Example:

  in [PPI]: val=1in [133]: val.__doc__ out[133]: "Int (x=0), int or long\nint (x, base=10), int or long  \n\nconvert a number or string to an integer, or return 0 if no arguments\nare given. If x is floating point, the conversion truncates towards zero.\nif x is outside the integer range, the function returns a Long instead.\n\nif x is not a number or if base was given, then x must am a string Or\nunicode object representing an inte  GER literal in the given base.  The\nliteral can is preceded by ' + ' or '-' and is surrounded by whitespace.\nthe base defaults to 10.  Valid bases is 0 and 2-36.  Base 0 means To\ninterpret the base from the string as a integer literal.\n>>> int (' 0b100 ', base=0) \n4 "in [134]: Val.bit_length () out[134]: 1In [135]: Type (val) out[135]: int This example __doc__ is the built-in property of the Int class, and bit_length () is the built-in method of the Int class. Val is an instance of the Int class  

Related built-in functions:
Type (object): Shows the types of objects
Dir ([object]): Displays the properties built into the object, and the supported methods (or actions)
Help (builtin. Object): To print assistance for the corresponding function, for example, to find the use Help for Bit_length (), enter "Assist (Val.bit_length)" or "Helps" (Int.bit_length "Because Val is an instance of the int class, so is the same code, and the Help document is the same

3. Data type

String:
What's special about a string in Python is that it's a sequence and it's an immutable object.
Example:

In [165]: s1=‘haha‘In [166]: s2=str(‘haha‘)In [167]: id(s1)Out[167]: 139910507684560In [168]: id(s2)Out[168]: 139910507684560In [169]: s1+s2Out[169]: ‘hahahaha‘不难看出,s1=‘haha‘和s2=str(‘haha‘)效果是一样的,str()其实就是字符类型的实例化函数,也是所谓的工厂函数,这里两种写法之所以等价,是因为python规定了一系列规则,使得解释器可以识别,这里相关的规则如下:    <1>数字不能作为变量名开头    <2>字符串赋值必须用‘‘、""、‘‘‘ ‘‘‘ 或者""" """括起来,(三个引号的可以换行)这些特殊使得解释器遇到没引号的字符是认为它是变量,而带引号则认为是字符。还有一点是当字符串出现在函数方法定义的第一行的时候,则表示对函数的_doc_属性赋值(这个属性相当于函数的简介),例子如下:    In [175]: def Testchar():     ...:     "it just a test"     ...:         In [176]: Testchar.__doc__    Out[176]: ‘it just a test‘

Boolean type:
Boolean type as in other languages, two values: True and False (capitalized)

Example:

In [187]: ‘2xxx‘ in sOut[187]: TrueIn [188]: a = 1 in sIn [189]: print aFalseIn [190]: a = ‘1‘ in sIn [191]: print aTrue因为"一切皆对象",变量只是对对象的引用,所以布尔类型也是赋值给变量,这里第一次a为False的原因在于,s里面的1是字符,不是数字

Integer, floating-point, Number:
These are nothing to say, ref: Http://www.cnblogs.com/linjiqin/p/3608541.html
Here's a copy of the corresponding function that might be useful

Numeric type conversion: Int (x [, Base]) converts x to an integer, float (x) converts x to a floating-point number complex (real [, Imag]) creates a plural str (x) to convert object X to string re PR (x) Converts an object x to an expression string, eval (str), which evaluates a valid Python expression in a string and returns an object tuple (s) converts the sequence s to a tuple list (s) to convert the sequence s to a list Chr (x Converts an integer to a character unichr (x) converts an integer to a Unicode character, Ord (x) converts a character to its integer value, Hex (x) converts an integer to a hexadecimal string, the OCT (x) converts an integer to a  Octal string math function: ABS (x) returns the absolute value of a number, such as ABS (-10) returns the number of Ceil (x) returned by the integer, such as Math.ceil (4.1) returns 5 cmp (x, y) if x < y returns -1, if x = = y returns 0 if x > y returns 1 exp (x) returns the x power of E (ex), such as MATH.EXP (1) return 2.718281828459045 fabs (x) returns the absolute value of the number, such as Ma    Th.fabs (-10) returns 10.0 floor (x) returns the number of the lower-rounding integer, such as Math.floor (4.9) returns 4 log (x) as Math.log (MATH.E) returns 1.0,math.log (100,10) returns 2.0    LOG10 (x) returns the logarithm of x with a base of 10, as MATH.LOG10 (100) returns 2.0 Max (x1, x2,...)    Returns the maximum value of a given parameter, which can be a sequence.    Min (x1, x2,...)    Returns the minimum value for a given parameter, which can be a sequence.    MODF (x) returns the integer part and fractional part of X, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type.    Pow (x, y) the value after the x**y operation.    Round (x [, N]) returns the rounding value of the floating-point number x, given the n value, which represents the digits rounded to the decimal point. sqrt(x) returns the square root of the number x, the number can be negative, and the return type is real, such as MATH.SQRT (4) returns 2+0J 

List:
The characteristic of a list is that its elements are mutable, and because it is a sequence, all methods that support a sequence
Element: The element here is actually an object, but it can be any type (so-called heterogeneous), simply not necessarily an integer or a string such as:
[[1, ' B '], ' B ', ' C ']
The list also contains a list of the set of elements enclosed in []

Example 1:

In [193]: l1=[‘1‘,‘2‘]In [194]: id(l1)Out[194]: 139910507832240In [195]: id(l1[0])Out[195]: 139910739440504In [196]: l1[0]="3"In [197]: print l1[‘3‘, ‘2‘]In [198]: id(l1[0])Out[198]: 139910738702424In [199]: id(l1)Out[199]: 139910507832240可以看出,在第一个元素发生变化的时候,l1引用的位置也是不变的,而l1[0]引用的位置则发生了变化

Example 2:

In [212]: l1=[‘1‘,‘2‘]In [213]: l2=l1In [214]: import copyIn [215]: l3=copy.deepcopy(l1)In [216]: print l2,l3[‘1‘, ‘2‘] [‘1‘, ‘2‘]In [217]: l1[0]=3In [218]: print l2,l3[3, ‘2‘] [‘1‘, ‘2‘]In [219]: id(l1)Out[219]: 139910507811688In [220]: id(l2)Out[220]: 139910507811688In [221]: id(l3)Out[221]: 139910509285672从例子可以看出l2=l1,其实是把l2指向到了l1的数据部分,也就是说l1和l2指向了相同的数据部分,而l3则是原样复制l1的数据,所以,当l1[0]变化时,l2[0]也会变化,l3则不变

Related built-in functions:
List.append (obj) adds a new object at the end of the list
List.count (obj) counts the number of occurrences of an element in a list
List.extend (SEQ) appends multiple values from another sequence at the end of the list (the original list is expanded with a new list)
List.index (obj) finds the index position of the first occurrence of a value from the list, starting at 0
List.insert (index, obj) inserts an object into the list
List.pop (obj=list[-1]) removes an element from the list (the last element by default) and returns the value of the element
List.remove (obj) removes the first occurrence of a value in a list
List.reverse () reverse list of elements, inverted
List.sort ([func]) to sort the original list

Meta-group:
Tuples are similar to lists (all collections of different elements), but their elements cannot be changed, and all operations of the sequence are supported, which are enclosed in ()

Example 1:

In [226]: a=([1,‘b‘],‘b‘,‘c‘)In [227]: a[2]=‘2‘---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-227-03bdd44bccdf> in <module>()----> 1 a[2]=‘2‘TypeError: ‘tuple‘ object does not support item assignment

Example 2:

In [228]: a=(1)In [229]: type(a)Out[229]: intIn [230]: a=(1,)In [231]: type(a)Out[231]: tuple当元组里面只有一个元素且是数字时,要加一个逗号,否则会被赋值为整型

Tuples built-in functions:
CMP (Tuple1, tuple2) compares two elements of tuples.
Len (tuple) calculates the number of tuple elements.
Max (tuple) returns the maximum value of the element in the tuple.
MIN (tuple) returns the element minimum value in the tuple.
A tuple (SEQ) converts a list to a tuple.

Dictionary: (Copy from: http://www.cnblogs.com/linjiqin/p/3608541.html)
The Dictionary (dictionary) is the most flexible built-in data structure type in Python, in addition to the list. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

字典由键和对应的值组成。字典也被称作关联数组或哈希表。基本语法如下:dict = {‘Alice‘: ‘2341‘, ‘Beth‘: ‘9102‘, ‘Cecil‘: ‘3258‘};也可如此创建字典:    dict1 = { ‘abc‘: 456 };    dict2 = { ‘abc‘: 123, 98.6: 37 };每个键与值必须用冒号隔开(:),每对用逗号分割,整体放在花括号中({})。键必须独一无二,但值则不必;值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。

Dictionary built-in functions:
CMP (Dict1, dict2) compares two dictionary elements.
Len (dict) calculates the number of dictionary elements, that is, the total number of keys.
The str (dict) output dictionary is a printable string representation.
Type (variable) returns the type of the variable entered, if the variable is a dictionary.
Radiansdict.clear () Delete all elements in the dictionary
Radiansdict.copy () returns a shallow copy of a dictionary
Radiansdict.fromkeys () Creates a new dictionary with the key of the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary
Radiansdict.get (key, Default=none) returns the value of the specified key if the value does not return the default value in the dictionary
Radiansdict.has_key (key) returns False if the key returns true in the dictionary Dict
Radiansdict.items () returns an array of traversed (key, value) tuples in a list
Radiansdict.keys () returns a dictionary of all keys in a list
Radiansdict.setdefault (Key, Default=none) is similar to get (), but if the key does not already exist in the dictionary, the key is added and the value is set to default
Radiansdict.update (DICT2) updates the dictionary dict2 key/value pairs to Dict
Radiansdict.values () returns all values in the dictionary as a list

Introduction to Python data types

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.