Chapter 2 python data types

Source: Internet
Author: User
Tags define local
Chapter 2 python data types section 1 numbers and string types

Is 123 the same as "123 "?

() [] {}

Computers are used to assist people. in programming, they also map real-world classifications for abstract analysis.

Number

String

List

Tuples

Dictionary

We can view some simple data types through data types. python will automatically identify the data types

>>> Num1 = 123
>>> Type (123)

>>> Type (num1)

>>> Num2 = 99999999999999999999999999
>>> Type (num2)

>>> Num = 'Hello'

>>> Type (num)

In python, the integer int indicates the range-2,147,483,648 to 2,147,483,647.

Example: 0,100, 100

The Int range example is shown above.

>>> Num3 = 123L here we assign values to long integers.
>>> Type (num3)

For 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 embedded support for plural numbers, which is not available in most other software:

Example of plural: 3.14j, 8.32e-36j

Example:

>>> Num = 3.14j
>>> Type (num)

>>> Num
3.14j
>>> Print num

3.14j

>>>

Here we determine the following two variables of different types

>>> A = 123
>>> Stra = "123"
>>> Print
123
>>> Print stra
123
>>> Here we find that the two variables of different types cannot be computed.
Traceback (most recent call last ):
File "", line 1, in
TypeError: unsupported operand type (s) for +: 'int' and 'str'
>>>
>>> Type ()

>>> Type (stra)

String

A set of numbers, letters, and symbols (non-special system symbols) that are defined by quotation marks.

>>> Str1 = 'Hello world'

>>> Str2 = "hello world"

>>> An error occurs when we define say = 'Let's go ', because we also include a single quotation mark.
File "", line 1
Say = 'Let's go'
^
SyntaxError: invalid syntax

>>> Say = "let's go". we can change the single quotation marks to double quotation marks.

>>> Say = "let's" go "" If there are double quotation marks in our double quotation marks, we need to use escape characters.
File "", line 1
Say = "let's" go ""
^
SyntaxError: invalid syntax
>>> Say = "let's \" go \""
>>> Print say

Let's "go"

The following describes how to use escape characters.

>>> Mail = 'Tom: hello I am jack'
>>> Print mail
Tom: hello I am jack
>>> Mail = 'Tom: \ n hello \ n I am jack '. if we want to output the above characters in the form of line breaks
>>> Mail
'Tom: \ n hello \ n I am Jack'
>>> Print mail
Tom:
Hello

I am jack

Below we use triple quotes to achieve the effect of line feed:

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

>>> Mail here we can see that when we use triple quotation marks, it will record our input.
'Tom: \ n \ ti am jack \ n goodbye \ n'

In addition, we can also use triple quotes to comment out a line in the code, or use it for doc data.

Index value

>>> A = 'ABCDE'

>>> A [0] we use indexes to retrieve a value in the string.

'A'
>>> A [1]
'B'
>>> A [0] + a [1] if we want to obtain multiple numbers, we can use the + number in the middle for connection.

'AB'

Use slice for value

>>>

'ABCDE'

Next let's take a look at the operations here. a [start position: end position + 1: step size]

>>> A [] Here we take bcd and use the [start position: end position + 1] value.

'Bcd'

>>> A [: 4] indicates that the disk is cut from the beginning to the end.

'ABCD'

>>> A [4:] removes the following value from the fourth position.

'E'

>>> A [2:]

'Cde'

>>> A [: 1] uses step size to set values. the following step size is clearer when it is 2.
'ABCDE'
>>> A [: 2]

'Acs'

>>> A [-4:-1] uses a negative index value. here we start from backward to backward, and-1 indicates the second to last.

'Bcd'

>>> A [:-1] is cut from the last value of the last one, and the previous value is displayed.

'ABCD'

The following two types of values can be seen:

>>> A [-2:-4:-1] switches all the numbers first, and then switches the value from the second position to the third position of 'DC '.
>>> A [-4:-2:1] indicates that the value is taken from the fourth position to the second position.

'BC'

>>> A [-2:-5:-1] returns the value.

'Dcb'

Section 2 sequence

A. the list, tuples, and strings are all sequences.

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

-- The index operator allows us to grasp a specific project from the sequence.

-- The slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.

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

-- Therefore, shoplist [-1] indicates the last element of the sequence, while shoplist [-2] captures the penultimate item of the sequence.

D. The slice operator is a sequence name followed by a square bracket, which contains an optional number and is separated by a colon.

-- Note that this is very similar to the index operator you are using. Remember that numbers are optional, while colons are required.

-- The first number in the slice operator (before the colon) indicates the start position, and the second number (after the colon) indicates the end of the slice. If the first number is not specified, Python starts from the beginning of the sequence. If the second number is not specified, Python stops at the end of the sequence.

-- Note: The Returned sequence starts from the starting position and ends just before the ending position. That is, the start position is included in the sequence slice, and the end position is excluded from the slice.

A. shoplist [] returns a sequence slice starting from position 1, including position 2, but stops at position 3. Therefore, returns a slice containing two items. Shoplist [:] returns a copy of the entire sequence. You can use a negative number for slicing. A negative number is used to start from the end of the sequence. For example, shoplist [:-1] returns a sequence slice that contains all projects except the last project.


Basic sequence operations

1. len (): calculates the sequence length.

2. +: connect two sequences

3. *: repeated sequence elements

4. in: determines whether the element is in the sequence.

5. max (): returns the maximum value.

6. min (): returns the smallest value.

7. cmp (tuplel, tuple2) compares the two sequence values for the same

Next we will perform the following operations:

>>>
'ABCDE'
>>> Len ()
5
>>> Str1 = '123'
>>> Str2 = 'adbs'
>>> Str1 + str2

'123adbs'

>>> Str1 * 5 so that str1 will be repeated five times

'123'
>>> "#" * 40
'####################################### #'
>>> Str2
'Adbs'

>>> 'C' in str2: Check whether the character 'C' is in the str2 string. if False is returned, True is returned.

False
>>> 'A' in str2
True

You can also use not in to determine whether the object is not in it.

>>> 'C' not in str2
True
>>> Max (str1)
'3'
>>> Max (str2)
'S'
>>> Min (str2)

'A'

Cmp (str1, str2) is used to compare two strings.

>>> Str1 = '123'
>>> Str2 = 'ABCDE'
>>> Cmp (str1, str2)

-1

>>> Str2 = '123'
>>> Cmp (str1, str2)
1
>>> Str2 = '000000' at this time, the two values are equal, and 0 is returned for comparison.
>>> Cmp (str1, str2)
0


Section 3 tuples ()

Tuples are similar to lists, except that tuples and strings are immutable, that is, you cannot modify them.

-- The tuples are defined by commas (,) in parentheses.

-- Tuples are usually used to securely use a group of values for statements or user-defined functions. that is, the values of the used tuples are not changed.

>>> Str2 = '123'
>>> Id (str2)
139702043552192
>>> Str2 = '123'
>>> Id (str2)

139702043552576

Next, we start the operation of tuples.

First, we can look at the name generated by slicing. it will be displayed with spaces when the length is different, so it is difficult for us to retrieve elements from it.

>>> Userinfo = "milo 30 male"
>>> Userinfo [: 4]
'Milo'
>>> Userinfo1 = "zou 25 famale"
>>> Userinfo1 [: 4]
'Zou'
>>> T = ("milo", 30, "male") if we use the definition of tuples here, it is much easier to set values.
>>> T [0]
'Milo'
>>> T [1]
30
>>> T [2]

'Male'


Create tuples
-- An empty tuples are composed of an empty pair of parentheses.
A. For example, myempty = ()
-- Tuples containing a single tuple
A. singleton = (2 ,)
-- Average tuples
A. zoo = ('Wolf ', 'Elephant', 'penguin ')

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

>>> T = () defines an empty tuples
>>> T1 = (2,) defines a tuples with only one element. Note that there must be no fewer commas.
>>> Type (t)

>>> Type (t1)


Tuples

-- Tuples and strings belong to the same sequence type, which can be indexed or sliced.

-- The values of the tuples are also unchangeable.

>>> T = ('Milo', 30, 'male ')
>>> T
('Milo', 30, 'male ')
>>> T [1]
30
>>> T [1] = 31 here, an error is reported when the age of the view is changed.
Traceback (most recent call last ):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> T

('Milo', 30, 'male ')

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

>>> A, B, c = 1, 2, 3

>>> A, B, c = (, 3) in python, the two methods can define tuples, but we try to use the second method.


Section 4 sequence-tuples

List []

1) list is the data structure that processes a group of ordered projects. you can store a series project in a list.

2) the list is variable-type data.

3) list composition: the list is represented by [], which contains multiple numbers or strings separated by commas.

-- List1 = ['Simon ', 'David', 'clotho', 'Zhang San']

-- List2 = [1, 2, 4, 5]

-- List3 = ["str1", "str2", "str3", "str4", "str5"]

>>> Listmilo = [] definition of an empty list
>>> Type (listmilo)

>>> Listmilo = ['Milo', 30, 'male'] General list definition
>>> T = ('Milo', 30, 'male ')
>>> T [0]
'Milo'
>>> Listmilo [0]
'Milo'
>>> Listmilo [0: 2] values from the list
['Milo', 30]
>>> T [0: 2]

('Milo', 30)

The differences are as follows:

>>> T3 = ('ABC ')
>>> L3 = ['ABC']
>>> Type (l3) here we can see that it is a list

>>> Type (t3)

List operations

-- Value

A. slice and index

B. list []

-- Add

A. list. append ()

-- Delete

A. del (list [])

B. list. remove (list [])

-- Modify

A. list [] = x

-- Search

A. var in list

>>> Listmilo [0] here we find that the value of the stored element can be changed in the list.
'Milo'
>>> Listmilo [0] = 'zou'
>>> Listmilo [0]
'Zou'

Next we will introduce how to add an element to the list.

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

['Milo', 30, 'male', '000000'] at this time, we found that the listmilo list has added the fourth element.

>>> Listmilo. remove ('20140901') deletes a value from the list.
>>> Listmilo
['Milo', 30, 'male']

>>> Del (listmilo [1]) you can also use del to delete values in the list through the list index.

>>> Listmilo
['Milo', 'male']

You need to learn how to use help to query the usage of some syntaxes. for example, you need to view the internal deletion operations of the list.

>>> 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 check the use of some internal functions


Object and class Quick start

1) objects and classes to better understand the list.

2) object = Property + method

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

-- When you use the variable I and assign values to it, such as assigning an integer 5, you can think that you have created an object (instance) I of the class (Type) int.

-- Help (int)

4) classes also have methods, that is, they define local functions only for classes.

-- These functions can be used only for objects of this class.

-- Example:

A. Python provides the append method for the list class. This method allows you to add a project at the end of the list.

B. add a string to mylist in mylist. append ('an item') list. Note: Use the DOT to use the object method.

5) classes also have variables, which are defined only for classes.

-- These variables/names can be used only for objects of this class.

-- Use the dot number, for example, mylist. field.


Section 5 dictionary {}

1) the dictionary is the only ing type (hash table) in python)

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

3) key () or values () return key list or value list

4) items () returns the tuples that contain key-value pairs.

Create a dictionary:

-{}

-Use the factory method dict ()

Example: fdict = dict (['X', 1], ['y', 2])

-Built-in method: fromkeys (). the elements in the dictionary have the same value. The default value is None.

Example: ddict ={}. fromkeys ('X', 'y'),-1)


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

>>> Dic1 = {'name': 'Milo', 'age': 25, 'gender': 'male'} it makes more sense to define

>>> Dic1 ['name'] is more purposeful only when values are set.
'Milo'
>>> Dic1 ['age']
25
>>> Dic1 ['gender']
'Male'

>>> Dic2 = {1: '000000', 'name': 'Milo', 'x': 123}

>>> Dic2

{1: '000000', 'name': 'Milo', 'x': 123}

Next, let's look at another example:

>>> A = 1 here we first define two variables
>>> B = 2

>>> Dic3 = {a: 'AAA', 'B': 'BBB'} if a is not defined, an error is returned.

>>> Dic3 [1]
'AAA'

>>> Dic3 [2] Here we finally see the difference. In fact, in the dictionary, it does not use the value defined before B.

Traceback (most recent call last ):
File "", line 1, in
KeyError: 2
>>> Dic3 ['B']
'BBB'
>>> Dic1
{'Gender': 'male', 'age': 25, 'name': 'Milo '}
>>> For k in dic1: Here we can see that it is convenient to use the dictionary.
... Print k
...
Gender
Age
Name
>>> For k in dic1:
... Dic1 [k] directly retrieve the value
...
'Male'
25
'Milo'


Update and delete:

-Directly use the key value to access updates. the built-in uodate () method can copy the entire dictionary content to another dictionary.

-Del dict1 ['A']: delete the element with the key value of a in the dictionary.

A. dict1.pop ('A') elements deleted with the return key 'A'

B. dict1.clear () delete all Dictionary elements

C. del dict1 delete the entire dictionary


>>> L
[1, 2, 3, 4, 5]
>>> L [5] = 7
Traceback (most recent call last ):
File "", line 1, in
IndexError: list assignment index out of range
>>> Dic1
{'Gender': 'male', 'age': 25, 'name': 'Milo '}
>>> Dic1 ['tel'] = '000000' here we can see that when using the dictionary, we can add a value without an error.
>>> Dic1
{'Gender': 'male', 'age': 25, 'tel': '000000', 'name': 'Milo '}

We can see that it is not added to the end, because the dictionary itself is not fixed, the dictionary is unordered, and the hash type value can be directly operated on the elements in the dictionary through the dictionary key.

>>> Dic1 ['tel'] = '000000'
>>> Dic1

{'Gender': 'male', 'age': 25, 'tel': '000000', 'name': 'Milo '}


>>> Dic1.pop ('age') pops up the value corresponding to the 'age' key. The dictionary does not contain the age key value.

25
>>> Dic1
{'Gender': 'male', 'Tel ': '000000', 'name': 'Milo '}
>>> Dic1.clear () clear the dictionary
>>> Dic1
{}
>>> Del (dic1) directly deletes the dictionary.
>>> Dic1
Traceback (most recent call last ):
File "", line 1, in
NameError: name 'dic1' is not defined


Built-in functions related to dictionaries:

-Type (), str (), cmp () (cmp is rarely used for dictionary comparison, and the values are the size, key, and value of the dictionary in sequence ).

Factory function dict ():

-Example: dict (zip ('X', 'y'), () or dict (x = 1, y = 2)

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

-Generating a dictionary using a dictionary is slower than using copy. Therefore, we recommend using copy () in this case ().


1) len (), hash () (used to determine whether an object can be used as a dictionary key. if it is not of the hash type, a TypeError error is reported ).

2) dict. clear (): delete all elements in the dictionary.

3) dict. fromkeys (seq, val = None): Creates a dictionary with the elements in seq as the key and returns a dictionary. val is the default value.

4) dict. get (key, default = None): return the value of the key. if the key does not exist, the value specified by default is returned.

5) dict. has_key (key): determines whether a key exists in the dictionary. we recommend that you use in and not in instead.

6) dict. items (): returns the list of key-value pairs.

7) dict. keys (): return the list of Middle keys in the dictionary.

8) dict. iter * (): iteritems (), iterkeys (), itervalues () return iteration rather than list.

9) dict. pop (key [, default]): Same as get (), the difference is that if the key exists, delete it and return its dict [key]. if the key does not exist, the default value is not specified, A KeyError is thrown.

10) dict. setdefault (key, default = None): Same as set (). if the key exists, its value is returned. if the key does not exist, dict [key] = default.

11) dict. update (dict2): add the key-value pairs in dict2 to the dictionary dict. if duplicate overwriting exists, add the entries that do not exist in the original dictionary.

12) dict. Values (): returns a list of all Dictionary values.


>>> Dic. get (3) view the dictionary

>>> Dic. get (3, 'error') when the dictionary does not exist, an error is returned.

'Error'

For other examples, we can use the help function.

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

The above is the content of the second chapter of python data type. For more information, please follow the PHP Chinese network (www.php1.cn )!

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.