Chapter II Python data types

Source: Internet
Author: User
Number and string types in the first section

123 and "123"?

() [] {}

Computers are used to assist people, and in programming they also map the real-world classification to facilitate abstract analysis.

Digital

String

List

Meta-group

Dictionary

We use data types to see some simple data types, and Python will automatically recognize the type of data

>>> num1=123
>>> Type (123)

>>> type (NUM1)

>>> num2=99999999999999999999999999
>>> type (num2)

>>> num= ' Hello '

>>> type (num)

integer int in python range-2,147,483,648 to 2,147,483,647

Example: 0,100,,100

An example of the range of int is shown above.

>>> num3=123l Here we're assigning values with long integers.
>>> type (NUM3)

Example: 0.0,12.0,,18.8,3e+7, etc.

Example:

>>> num=0.0
>>> type (num)

>>> num=12
>>> type (num)

>>> num=12.0
>>> type (num)

Python provides inline support for complex numbers, which is not available in most other software:

Plural examples: 3.14j,8.32e-36j

Example:

>>> num=3.14j
>>> type (num)

>>> num
3.14j
>>> Print num

3.14j

>>>

Here we judge the following two different types of variables

>>> a=123
>>> stra= "123"
>>> Print a
123
>>> Print Stra
123
>>> A+stra Here we find that these two different types of variables cannot be calculated
Traceback (most recent):
File "", Line 1, in
typeerror:unsupported operand type (s) for +: ' int ' and ' str '
>>>
>>> type (a)

>>> type (stra)

Strings string

A set of quotation marks that can contain a collection of numbers, letters, symbols (non-special system symbols).

>>> str1= ' Hello World '

>>> str2= "Hello World"

>>> say= ' Let's go ' this defines an error, because when we define it here we also include a single quote
File "", Line 1
Say= ' let ' s go
^
Syntaxerror:invalid syntax

>>> say= "Let's go" we'll change the outer single quote to double quotation marks.

>>> say= "Let's" go "if we have double quotes inside our double quotes, we're going to use the escape character.
File "", Line 1
Say= "Let ' s" Go ""
^
Syntaxerror:invalid syntax
>>> say= "Let ' s \" Go\ ""
>>> print say

Let ' s "go"

Let's look at some of the use of escape characters

>>> mail= ' Tom:hello I am Jack '
>>> Print Mail
Tom:hello I am Jack
>>> mail= ' tom:\n hello\n I Am Jack ' for the above characters if we want to use the form of line break output
>>> Mail
' Tom:\n hello\n I Am Jack '
>>> Print Mail
Tom
Hello

I am Jack

Here we use triple quotes to achieve the effect of line wrapping:

>>> mail= "" "Tom:
... I am jack
... goodbye
... """
>>> Print Mail
Tom
I am Jack
Goodbye

>>> Mail Here we can see that when we use triple quotes, he'll record our input.
' Tom:\n\ti am jack\n goodbye\n '

In addition, we can use the triple quotation marks to comment on a line in the code, or we can do the doc data with him.

Value by index

>>> a= ' ABCDE '

>>> A[0] We use an index to fetch a value inside a string.

A
>>> A[1]
' B '
>>> A[0]+a[1] If we want to take more than one can use the + sign in the middle to do the connection

' AB '

Using slices to take values

>>> A

' ABCDE '

Let's take a look at the operation here, a[start position: End position + 1: Step length]

>>> A[1:4] Here we take the BCD, to use [start position: End position +1] to take the value

' BCD '

>>> A[:4] This means cutting from the beginning to the D

' ABCD '

>>> a[4:] from the fourth position here to cut back the value

E

>>> a[2:]

' CDE '

>>> A[::1] To take the step size, the following step is 2 more clear
' ABCDE '
>>> A[::2]

' Ace '

>>> a[-4:-1] by negative index, here we start from the back forward, 1 for the second-to-last value

' BCD '

>>> A[:-1] cut off from the last value and display the previous value

' ABCD '

Here are two ways we can see the order of his values.

>>> A[-2:-4:-1] He is starting from the second position of all the numbers in turn and then starting to cut the value to ' DC ' third position
>>> A[-4:-2:1] He said to start at the bottom of the fourth position to take the value to the penultimate position to cut

' BC '

>>> a[-2:-5:-1] upside-down value

' DCB '

Second section sequence

A. Lists, tuples, and strings are sequences

B. The two main features of a sequence are index operators and slice operators.

--The index operator allows us to grab a specific item from the sequence.

--The slice operator allows us to get a slice of the sequence, which is part of the sequence.

C. The index can also be negative, and the position is calculated from the end of the sequence.

--therefore, shoplist[-1] represents the last element of the sequence and Shoplist[-2] The penultimate item of the crawl sequence

D. The slice operator is a sequence name followed by a square bracket, with a pair of optional digits in the square brackets, separated by a colon.

Note that this is very similar to the index operator you are using. Remember that the number is optional, and the colon is required.

--The first number in the slice operator (preceded by a colon) represents the starting position, and the second number (after the colon) indicates where the slice ends. If you do not specify the first number, Python starts from the beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence.

-NOTE: The returned sequence starts at the starting position and ends just before the end position. That is, the start position is contained in the sequence slice, and the end position is excluded from the slice.

A.shoplist[1:3] Returns a slice that contains two items, starting at position 1, including position 2, but stopping a sequence slice at position 3. Shoplist[:] Returns a copy of the entire sequence. You can make slices with negative numbers. Negative numbers are used at the beginning of the end of the sequence. For example, shoplist[:-1] Returns a sequence slice that contains all the items except for the last item.


Basic operation of the sequence

1.len (): Find the sequence length

2.+: Connecting 2 sequences

3.*: Repeating sequence elements

4.in: Determine if the element is in sequence

5.max (): Returns the maximum value

6.min (): Returns the minimum value

7.CMP (Tuplel,tuple2) Compare 2 series values are the same

Let's take a look at the following:

>>> A
' ABCDE '
>>> Len (a)
5
>>> str1= ' 123 '
>>> str2= ' Adbs '
>>> STR1+STR2

' 123adbs '

>>> str1*5 So str1 will be repeated five times

' 123123123123123 '
>>> "#" *40
'########################################'
>>> str2
' Adbs '

>>> ' C ' in str2 to see if the ' C ' character is not returning false in str2 this string, in return True

False
>>> ' a ' in str2
True

You can also use not in to determine that it is not inside

>>> ' C ' not in str2
True
>>> Max (STR1)
' 3 '
>>> Max (STR2)
' s '
>>> min (str2)

A

CMP (STR1,STR2) For comparison of two strings

>>> str1= ' 12345 '
>>> str2= ' ABCDE '
>>> CMP (STR1,STR2)

-1

>>> str2= ' 123 '
>>> CMP (STR1,STR2)
1
>>> str2= ' 12345 ' at this point two values are equal and the comparison returns 0
>>> CMP (STR1,STR2)
0


Section three, tuple ()

Tuples and lists are very similar, except that tuples and strings are immutable, meaning that you cannot modify tuples.

--The tuple is defined by a comma-separated item in parentheses.

--tuples are typically used when a statement or user-defined function can safely take a set of values, that is, the value of the tuple being used does not change.

>>> str2= ' 12345 '
>>> ID (STR2)
139702043552192
>>> str2= ' 123456666 '
>>> ID (STR2)

139702043552576

Let's begin the operation of the tuple

First of all, we can look at the name through the slices, will be in the case of different lengths of space to display, so we take elements from the inside is more difficult

>>> userinfo= "Milo Male"
>>> Userinfo[:4]
' Milo '
>>> userinfo1= "Zou Famale"
>>> Userinfo1[:4]
' Zou '
>>> t= ("Milo", +, "male") here if we use tuples as a way of defining this, it's a lot easier when you take a value.
>>> T[0]
' Milo '
>>> T[1]
30
>>> T[2]

' Male '


Creating tuples
--An empty tuple consists of a pair of empty parentheses
A. If Myempty = ()
--tuples containing a single tuple
A.singleton = (2,)
--General tuples
A.zoo = (' Wolf ', ' Elephant ', ' penguin ')

B.new_zoo = (' monkey ', ' Dolphin ', zoo)

>>> t= () defines an empty tuple
>>> t1= (2,) defines a tuple that has only one element, so pay special attention to that comma, not less
>>> type (t)

>>> type (t1)


Tuple operations

--tuples and string types belong to sequence types, and can be manipulated by index and slice

--The tuple value is also immutable

>>> t= (' Milo ', ' Male ')
>>> T
(' Milo ', +, ' male ')
>>> T[1]
30
>>> t[1]=31 Here we find an error when the view changes age
Traceback (most recent):
File "", Line 1, in
TypeError: ' Tuple ' object does not support item assignment
>>> T

(' Milo ', +, ' male ')

>>> name,age,gender=t
>>> Name
' Milo '
>>> Age
30
>>> gender
' Male '

>>> a,b,c=1,2,3

>>> a,b,c= (three-way) in Python both methods can define tuples, but we try to use the second method


Fourth section sequence-tuples

list []

1) list is the data structure that handles a set of ordered items, that is, you can store a sequence of items in a list.

2) List is a mutable type of data

3) The list consists of a list with [] that contains multiple comma-separated numbers, or strings.

--list1=[' Simon ', ' David ', ' Clotho ', ' Zhang San '

--list2=[1,2,3,4,5]

--list3=["str1", "str2", "Str3", "STR4", "STR5"]

>>> listmilo=[] Empty list definition
>>> type (Listmilo)

>>> listmilo=[' Milo ', (+, ' male ') Definition of general list
>>> t= (' Milo ', ' Male ')
>>> T[0]
' Milo '
>>> Listmilo[0]
' Milo '
>>> Listmilo[0:2] to take a value from the list
[' Milo ', 30]
>>> T[0:2]

(' Milo ', 30)

There's a difference here.

>>> t3= (' abc ')
>>> l3=[' abc ']
>>> type (L3) Here we can see that he is a list

>>> type (T3)

List operations

--Take value

A. Slices and indexes

B.list[]

--Add

A.list.append ()

--Delete

A.del (list[])

B.list.remove (list[])

--Modification

A.list[]=x

--Find

A.var in List

>>> Listmilo[0] Here we find that the list can change the value of the stored element
' Milo '
>>> listmilo[0]= ' Zou '
>>> Listmilo[0]
' Zou '

Let's look at how to add an element to the list

>>> Listmilo
[' Milo ', +, ' male ']
>>> listmilo.append ("123444555")
>>> Listmilo

[' Milo ', ', ' Male ', ' 123444555 '] at this point we find that the fourth element has been added to the Listmilo list

>>> listmilo.remove (' 123444555 ') remove a value from the list
>>> Listmilo
[' Milo ', +, ' male ']

>>> del (listmilo[1]) We can also use Del to remove values from the list by using the index of the list

>>> Listmilo
[' Milo ', ' Male ']

To learn how to use Help to query some syntax usage, for example, we need to see the inside of the list of delete operations

>>> Help (List.remove)


Help on Method_descriptor:

Remove (...)
L.remove (value)--Remove first occurrence of value.
Raises valueerror if the value is not present.
(END)

>>> Help (Len) to see the use of some intrinsic functions


Quick start for objects and classes

1) objects and classes, a better understanding of the list.

2) Object = attribute + method

3) A list is an example of using objects and classes.

When you use the variable i and assign it a value, such as assigning an integer of 5, you can assume that you have created an object (instance) I of a class (type) int.

--help (int)

4) Classes also have methods that define the ground function only for the class.

--only objects of this class can use these features.

-For example:

A.python provides the Append method for the list class, which allows you to add an item at the end of the listing.

B.mylist.append (' an item ') adds a string to the list mylist. Note that you use the point number to use the object's methods.

5) Classes also have variables that are defined only for classes.

--only objects of this class can use these variables/names.

--Use a dot number, such as Mylist.field.


Fifth section Dictionary {}

1) dictionary is the only mapping type (hash table) in Python

2) The Dictionary object is mutable, but the key of the dictionary must use the immutable object, and the different types of key values can be used in a dictionary.

3) key () or values () returns the key list or the value list

4) items () returns a tuple containing key-value pairs.

To create a dictionary:

- {}

-Using the Factory Method Dict ()

Example: Fdict=dict ([' X ', 1],[' Y ', 2])

-Built-in method: Fromkeys (), the element in the dictionary has the same value, the default is None

Example: Ddict={}.fromkeys ((' x ', ' Y '),-1)


>>> Dic={0:0,1:1,2:2} Here we define a dictionary {Key:value,key:value,key:value}
>>> Dic[0]
0
>>> Dic[1]
1
>>> Dic[2]
2

>>> dic1={' name ': ' Milo ', ' Age ': ' Gender ': ' Male ' is more meaningful by definition

>>> dic1[' name '] We're more purposeful when we take value.
' Milo '
>>> dic1[' age ']
25
>>> dic1[' gender ']
' Male '

>>> dic2={1: ' 123 ', ' name ': ' Milo ', ' X ': 456}

>>> Dic2

{1: ' 123 ', ' name ': ' Milo ', ' X ': 456}

Next we look at another example:

>>> A=1 Here we define two variables first
>>> b=2

>>> dic3={a: ' aaa ', ' B ': ' BBB '} If a is not defined this will cause an error.

>>> Dic3[1]
' AAA '

>>> Dic3[2] Here we finally see the difference, actually in the dictionary, he did not use the value defined before B

Traceback (most recent):
File "", Line 1, in
Keyerror:2
>>> dic3[' B ']
' BBB '
>>> Dic1
{' Gender ': ' Male ', ' age ': +, ' name ': ' Milo '}
>>> for K in Dic1: Here we can see the convenience of using a dictionary
... print K
...
Gender
Age
Name
>>> for K in Dic1:
... dic1[k] Direct fetch value
...
' Male '
25
' Milo '


Update and delete:

-Access updates directly with key values; The built-in Uodate () method copies the contents of the entire dictionary to another dictionary.

-Del dict1[' a '] removes the element with a key value of a in the dictionary

A. Dict1.pop (' a ') delete and return the element with the key ' a '

B. dict1.clear () Delete all elements of the dictionary

C. del Dict1 Delete entire dictionary


>>> L
[1, 2, 3, 4, 5]
>>> l[5]=7
Traceback (most recent):
File "", Line 1, in
Indexerror:list Assignment index out of range
>>> Dic1
{' Gender ': ' Male ', ' age ': +, ' name ': ' Milo '}
>>> dic1[' tel ']= ' 123454565 ' here we see that when using a dictionary it is possible to add a value without an error
>>> Dic1
{' Gender ': ' Male ', ' age ': ' Tel ': ' 123454565 ', ' name ': ' Milo '}

We see that he is not added to the last side, because the dictionary itself is not fixed, the dictionary of disorder, the value of the hash type, through the dictionary key can directly manipulate the elements of the dictionary

>>> dic1[' tel ']= ' 888888888 '
>>> Dic1

{' Gender ': ' Male ', ' age ': ' Tel ': ' 888888888 ', ' name ': ' Milo '}


>>> dic1.pop (' Age ') pops up the value of the key, the dictionary does not have the

25
>>> Dic1
{' Gender ': ' Male ', ' tel ': ' 888888888 ', ' name ': ' Milo '}
>>> dic1.clear () Empty dictionary
>>> Dic1
{}
>>> del (DIC1) Delete dictionary directly
>>> Dic1
Traceback (most recent):
File "", Line 1, in
Nameerror:name ' Dic1 ' is not defined


Dictionary-related built-in functions:

-type (), str (), CMP () (CMP is seldom used for dictionary comparisons, which in turn are dictionary sizes, keys, values).

Factory function Dict ():

-For example: Dict (Zip (' x ', ' Y '), ()) or dict (x=1,y=2)

-{' Y ': 2, ' X ': 1}

-Using a dictionary to generate a dictionary is slower than copy, so it is recommended to use copy () in this case.


1) Len (), hash () (used to determine whether an object can do a dictionary key, non-hash type report typeerror error).

2) Dict.clear (): Deletes all the elements in the dictionary.

3) Dict.fromkeys (Seq,val=none): Creates and returns a dictionary with the element in SEQ as the key, Val for the set default value.

4) Dict.get (Key,default=none): Returns the value of key, if the key does not exist, returns the values specified by default.

5) Dict.has_key (key): To determine if there is a key in the dictionary, it is recommended to use in and not instead.

6) Dict. Items (): Returns a list of key-value pairs of tuples.

7) Dict.keys (): Returns the list of keys in the dictionary.

8) dict.iter* (): Iteritems (), Iterkeys (), Itervalues () returns the iteration instead of the list.

9) Dict.pop (Key[,default]): Same as Get (), the difference is if the key exists, delete and return its dict[key], if there is no tangent to the default value is not specified, throw a Keyerror exception.

Dict.setdefault (key,default=none): Same set (), returns its value if key exists, or Dict[key]=default if key does not exist.

Dict.update (DICT2): Adds a key-value pair from Dict2 to the dictionary dict, and if there is a duplicate overwrite, an entry that does not exist in the original dictionary is added.

) Dict. VALUES (): Returns a list of all values in the dictionary.


>>> Dic.get (3) We look at the dictionary

>>> dic.get (3, ' error ') when the dictionary does not exist, the definition returns an error

' Error '

Other examples we can practice, if not understand we can use the help this function.

>>> dic1={' A ': 123, ' B ': 456,1:111,4:444}
>>> Dic1.keys ()
[' A ', 1, ' B ', 4]
>>> dic1.values ()
[123, 111, 456, 444]

The above is the second chapter of Python data type content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.