Data types for Python

Source: Internet
Author: User

Python's data types include basic data types such as: Integer, Float, String, string and advanced data types such as lists, tuples, dictionaries, set,forzensets.

I. Integral type

Python can handle integers of any size, including negative integers.
In Python 2.x, there are two types of integers, general 32-bit integers and long integers, long integers are expressed as L or L, and more than 32 bits are automatically converted to long-shaped. In Python 3.x, there is only one type and no length limit.

In Python 2.x, there are two ways to denote octal, one is to add 0 directly to the number, such as 010, plus 0o (0 and lowercase o), as in other programming languages, such as 0o10. In Python 3.x, there is only one way to represent octal, which is the beginning of 0o.

The hexadecimal representation method starts with 0x, such as 0x10.

Two. Floating point number

Floating-point numbers are decimals, which is called floating-point numbers because, when represented by scientific notation, the decimal position of a floating-point number is variable, for example, 1.23x10^9 and 12.3x10^8 are equal. Floating-point numbers can be written in mathematical notation, such as,, 1.23 3.14 , and -9.01 so on. But for very large or very small floating-point numbers, it must be expressed in scientific notation, the 10 is replaced with E, 1.23x10^9 is 1.23e9, or 12.3e8, 0.000012 can be written 1.2e-5, and so on.

Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! ), and the floating-point operation may have rounding errors.

Three. String

Strings are ‘‘ arbitrary text in or around "" them, such as ' abc ', 'xyz ', and so on.

In addition, the string can be identified in a pair of three quotation marks: "" "or" ". In three quotation marks, the line is not escaped, they are already included in the string:

Print ("" \ Usage:thingy [OPTIONS]-H Display this Usage message-h hostname Hostname to connect to "" ")

Get the following output:

usage:thingy [OPTIONS]-H Display This usage message-h hostname hostname to Connect to

You can use a backslash to end a continuous string for the line, which indicates that the next line is logically the subsequent content of the bank

>>> a= "" "AAA ... bbb ... "" ">>> print aaaabbbccc>>>

Strings provide a number of built-in functions that are useful in many Python programs, including:
EndsWith () – checks whether the string ends with the given string
StartsWith () – checks whether the string starts with the given string
Upper () – Converts all characters of a string into uppercase
Lower () – converts all characters of a string into lowercase
Isupper ()/islower () – detects if the string is all uppercase/lowercase
Len () – Detects string lengths

>>> print ("abc". EndsWith (' C ')) true>>> print ("abc". StartsWith (' C ')) false>>> print ("abc" . StartsWith (' a ')) true>>> print (' a '. Upper ()) a>>> print (A.isupper ()) false>>> print (Len (" ABC ")) 3
Four. Boolean values

The Boolean value is exactly the same as the Boolean algebra, with a Boolean value of only true, false two, or true, or false, in Python, which can be used to indicate a Boolean value directly with True, false (note case), or by Boolean operations.

Boolean values can be operated with and, or, and not.
The and operation is associated with an operation, and only the result of all true,and operations is True.
An OR operation is an operation, as long as one of the true,or operation results is True.
The not operation is a non-operation, which is a single-mesh operator that turns true to False,false to true.

Five. Null value

The null value is a special value in Python, denoted by none. None cannot be understood as 0, because 0 is meaningful, and none is a special null value.

Six. List

A list is a data type built into Python that uses "[]" to indicate that a list is an ordered collection that can add and remove elements at any time.

1. Create a list

Constructing the list is very simple, just using [] to enclose all the elements of the list, which is a list object. In general, we assign a list to a variable so that we can refer to the list by a variable:

>>> classmates = [' Jlan ', ' Bob ', ' Lanny ']>>> classmates # Print the contents of the classmates variable [' Jlan ', ' Bob ', ' Lanny ']

You can also use list constructors to create our lists, such as:
>>> list (' a ')
[' A ']
>>> values = (1,2,3,4) #values是一个元组
>>> list (values)
[1,2,3,4]

Because Python is a dynamic language, the elements contained in the list do not necessarily require the same data type, and we can include all kinds of data in the list:

>>> L = [' Jlan ', 170, 65]

An element that does not have a list is an empty list:

>>> empty_list = []
2. Index operations
>>> L = [' Jlan ', ' Bob ', ' Lanny '] # L[0]=jlan,l[1]=bob,l[-1]=lanny
3. Slicing operations
 >>> l=range (Ten) >>> l[0, 1, 2, 3, 4, 5, 6,  7, 8, 9]>>> l[0:3][0, 1, 2]>>> l[:3][0, 1, 2]> >> l[:]                              #只用一个 ":" means from beginning to end [0, 1, 2 ,  3, 4, 5, 6, 7, 8, 9]>>> l[1:][1, 2, 3, 4,  5, 6, 7, 8, 9]>>> l[::2]                             #第三个参数表示每N个取一个 [0, 2, 4, 6, 8]>>> l[:5:2][0, 2, 4]>> > L[-1]9>>> L[-5:-1][5, 6, 7, 8]>>> L[-5:-1:2][5, 7] 
4. Add Delete and modify data

The list's append () method always adds a new element to the end of the list:

>>> L = [' Jlan ', ' Bob ', ' Lanny ']>>> l.append (' Paul ') >>> print l[' Jlan ', ' Bob ', ' Lanny ', ' Paul ' ]

The parameters of the append () can also be a list, such as:

>>> l1=[1,2,3]>>> l2=[4,5,6]>>> l1.append (L2) >>>l1.extend (L2 ) #注意append和extend的区别 [1, 2, 3, [4, 5, 6]] [1,2,3,4,5,6]

To add to the specified location, use the Insert () method of list, which accepts two parameters, the first parameter is the index number, and the second parameter is the new element to be added:

>>> L = [' Jlan ', ' Bob ', ' Lanny ']>>> l.insert (0, ' Paul ') >>> print l[' Paul ', ' Jlan ', ' Bob ', ' Lann Y ']

List.pop (n) deletes the n+1 element in the current list and returns LIST[N+1]
List.remove (key) removes the value from list key

Delete a repeating element in a list
It's easier to remember with built-in set

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = List (set (L1)) print L2

There's another one that's said to be faster.

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = {}.fromkeys (L1). Keys () Print L2

Both have a drawback, and the sorting changes after removing the repeating elements:

[' A ', ' C ', ' B ', ' d ']

If you want to keep their original sort:
Using the Sort method of the list class

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = List (set (L1)) L2.sort (key=l1.index) Print L2

Or

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = sorted (set (L1), key=l1.index) print L2

You can also use traverse

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = []for i in L1:if don't I in L2:l2.append (i) Print L2

The code above can also be written like this

L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = [][l2.append (i) for I in L1 if not I in L2]print L2

This will ensure that the sort is unchanged:

[' B ', ' C ', ' d ', ' a ']
Seven. Tuples

Tuples (tumple) are another type of serialized table in Python, but the values of tuples are immutable, and tuples are denoted by "()"

>>> t= (' Jlan ', ' Bob ', ' Lanny ') >>> t (' Jlan ', ' Bob ', ' Lanny ') >>> t[1]= ' Hary ' Traceback (most Recent call last): File "", Line 1, in TypeError: ' Tuple ' object does not support item assignment

We saw in the front that the tuple cannot be modified once it is created, so let's look at a "mutable" tuple:

>>> t = (' A ', ' B ', [' A ', ' B ']) #t有3个元素: ' A ', ' B ' and a list:[' a ', ' B ']>>> L = t[2]>>> l[0] = ' X ' #然后, change the list's two elements >>> l[1] = ' Y ' >>> print t #再看看tuple的内容 (' A ', ' B ', [' X ', ' Y '])

When the tuple has only one element, add a "," or the tuple will be treated as a numeric value or a string, such as:

>>> t= (1) >>> t1>>> t= (1,) >>> T (1,)
Eight. Dictionaries

Dictionary with "{key1:value1,key2:value2,......}" in Python Format, where key is immutable and there is no order between the key-value.
Dict is very common in python, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object, the most commonly used key 10 string.
in Python, strings, integers, and so on are immutable, so it's safe to be a key. The list is mutable and cannot be a key.

>>> grade={' Jlan ': +, ' lanny ':, ' Bob ': 98, ' Hary ': ", ' Alan ': 80}>>> print grade {' Bob ': 98,  ' lanny ': 99,  ' Alan ': 80,  ' Hary ': 96,  ' Jlan ': 100}> >> grade[' Bob ']98>>> print grade.get (' Alan ')                    #python3中已没有这种用法80 >>>print  Grade.get (' Jlan ', -1)                #若 ' Jlan ' in grade, return grade[' Jlan '); if not, return None or a custom value 100>>> grade[' Rob ']=60                               #添加元素 >>>grade.pop (' Bob ')                               #删除元素, List.Pop is a function, so use ' () ' instead of ' [] ' >>> grade{' Rob ': 60,  ' Alan ': 80,  ' Jlan ':  100,   ' Hary ': 96,  ' lanny ':  99}

The traversal of the dictionary:

grade={' Jlan ': +, ' lanny ':, ' Bob ': 98, ' Hary ': ", ' Alan ': 80}for key in Grade:print key+ ': ', Grade[key]bob:98lanny: 99alan:80hary:96jlan:100

Nine. Set

The internal structure of set is much like the dict, the only difference is that it does not store value, so it is very fast to determine whether an element is in set.
The set stored element is similar to the Dict key, and must be an immutable object, so any mutable object cannot be placed in the set.
Finally, the set stores the elements that are not in order.
To create a set, you need to provide a list as the input collection:

>>> s = Set ([1, 2,3, 3]) >>> sset ([1, 2, 3])

#set会自动过滤重复元素
>>>s.add (4) #add (key) add element
>>>print s
Set ([1, 2, 3, 4,]
>>>s.remove (1) #remove (key) Delete element
>>>s
Set ([2, 3, 4]

10. Re-discuss non-mutable objects

As we said above, Str,tumple is an immutable object, and list is a mutable object.
For mutable objects, such as list, to manipulate the list, the contents of the list will change, such as:

>>> a = [' C ', ' B ', ' A ']>>> a.sort () >>> a[' A ', ' B ', ' C ']

For non-mutable objects, such as STR, we operate on STR:

>>> a = ' abc ' >>> a.replace (' A ', ' a ') ' abc ' >>> a ' abc '

Although the string has a replace () method, it does change the ' ABC ', but the variable A is still ' abc ', how should it be understood?
Let's start by changing the code to the following:

>>> a = ' abc ' >>> b = a.replace (' A ', ' a ') >>> B ' abc ' >>> a ' abc '

Always keep in mind that a is a variable, and that ' abc ' is a String Object! Sometimes, we often say that the content of object A is ' abc ', but in fact it means that a is itself a variable, it points to the content of the object is ' abc '.
When we call A.replace (' A ', ' a '), the actual calling method replace is on the string object ' abc ', and this method, although named Replace, does not change the contents of the string ' abc '. Instead, the Replace method creates a new string ' abc ' and returns, if we point to the new string with variable B, it's easy to understand that variable a still points to the original string ' abc ', but the variable B points to the new string ' abc '.
Therefore, for an immutable object, any method that invokes the object itself does not change the contents of the object itself. Instead, these methods create a new object and return it, ensuring that the immutable object itself is always immutable.


Data types for Python

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.