Python Guide: Combining data types __python

Source: Internet
Author: User
Tags extend iterable set set shallow copy

1, Sequence type 1.1-tuple 1.1.1.1 Tuple index and fragment 2.1.1 Tuple operators 3.1.1 Tuple operator 4.1.1 Tuples Deletion 1.1.6 no close separator 5 named tuple 1.2 list 1.3.1 List creation 1.3.2 List index and Fragment 1.3.3 list method 1.3.4 split operator 1.3.5 Delete 1.3.6 list connotation 2, collection type 2.1 set 2.1.1 set of sets of 2.1.2 collection method and operator 2.1.3 set connotation 2.2 fixed set 3, mapping Type 3. 1 Dictionary of 3.1.1 Dictionary Creation 3.1.2 Dictionary method 3.1.3 Dictionary connotation 3.2 default dictionary 3.3 ordered dictionary 4, iteration and replication of combined data Types 4.1 iterations, iteration operations, and Function 4.2 combination type replication

In this chapter, we'll learn how to aggregate data items together using Python's combined data types so that you have more options when designing.

1. Sequence type

Python provides the sequence types built into 5:bytearray,bytes,list,str , and tuple, The sequence type supports the member relation operator (in), the size calculation function (len ()), the Fragment ([]), and is the cocoa iteration. 1.1 Yuan Group

A tuple is an ordered sequence that contains 0 or more object references, wrapped with parentheses. The tuple is fixed and cannot replace or delete any of the data items it contains. 1.1.1-Tuple creation

Use () to create a tuple: no content in parentheses, create a null tuple with a comma-delimited set of data items, create a non-empty tuple

You can also use tuple () to create a tuple that returns an empty tuple when you use tuple as a parameter, when you return a shallow copy of another parameter of the argument, try to convert the given object to a tuple type 1.1.2 tuple index and fragment

Grammar Description
TUP[1] Reading a second element
Tup[-2] Reverse read; Read the penultimate element
Tup[1:] Intercepting elements
Tup = (' 5, ' white ', ' dog ') print

(tup[1]) print (
tup[-2) print (
tup[1:])

[out]
5
White
(5, ' white ', ' dog ')
1.1.3-Tuple Method

Tuples provide only two ways:

Grammar Description
T.count(x) Returns the number of times the object x appears in Ganso t
T.index(x) Returns the leftmost position that object x appears in a tuple t
Tup = (' 1 ', ' A ', ' 1 ', ' 1 ', ' 2 ')
print (' Count of ' 1 ': ', Tup.count (' 1 '))
print (' Index of ' 2 ": ', Tup.index (' 2 '))" C2/>[out]
Count of "1": 3
Index of "2": 4
1.1.4-tuple operator

As with strings, the + and * numbers can be used between tuples. This means that they can be combined and copied, and a new tuple will be generated after the operation.

Grammar Description
Len (t) Returns the number of elements in a tuple t
+ Connection
* Copy
In Whether an element exists
For ... in ...: Iterations
Comparison operators
<, <=, >, >=, = =,!=
Comparison by item
1.1. Deletion of the 5-tuple group

The element values in the tuple are not allowed to be deleted, but we can use del to delete the entire tuple:

Tup = (' python ', ' Hello ', 1997, Watts);
Print (tup)

del tup
print ("After deleting Tup:")
print (tup)

[out]
(' python ', ' Hello ', 1997, 2000) After
deleting tup: 
---------------------------------------------------------------------------
Nameerror                                 Traceback (most recent call last)
<ipython-input-1-a12bbf13863f> in <module> ()
      4 Del tup
      5 print ("After deleting Tup:")
----> 6 print (tup)

nameerror:name ' tup ' are not defined
1.1.6 No Close separator

You do not use parentheses when the tuple appears to the left of the binary operator or to the right of the unary statement .

A,b = (1,2) # Left of binary operator
to X,y in ((1,2), (3,4), (5,6)): # Left of binary operator
    print (x,y)

Del A,b # Right of unary statement
def f (x): Return
    x,x**2 # right of unary statement
1.2 named tuples

A named tuple (namedtuple), like a normal tuple, has the same performance feature that it adds to the ability to refer to an item in a tuple by name .

The Collections module provides a namedtuple () function to create a custom tuple data type. The first parameter of the function is the name of the custom tuple data type that you want to create, and the second parameter is a string that contains a space-delimited name that represents an entry in the metadata type for that primitive. This function returns a custom class that can be used to create a named tuple.

Import collections
Sale = Collections.namedtuple (' Sale ', ' ProductID CustomerID Data Quantity price ')
sales = List ()
sales.append (Sale (432,921, "2018-04-01", 3,8.2))
sales.append (Sale (543,879, "2018-03-31", 6,8.1))
Print (sales)

[out]
[Sale (productid=432, customerid=921, Data= ' 2018-04-01 ', quantity=3, price=8.2), Sale (productid=543, customerid=879, Data= ' 2018-03-31 ', quantity=6, price=8.1)]

Here we create a list of two sale items that we can use to refer to the items in a tuple, or to use names to refer to, which are the characteristics of the formally named tuple:

Total = 0 for
sale in Sales: total
    + = sale.quantity * Sale.price
print (' total¥{0:.2f} '. Format (total)) C14/>[out]
total¥73.20
1.3 List

A list is an ordered sequence of 0 or more object references, supporting the same fragment and step syntax as strings and tuples, so that we can Delete or replace items in the list, and it is possible to insert, replace, or delete the fragments in the list. 1.3.1 The creation of a list

Use [] to create a tuple with no content in parentheses, create an empty list parentheses containing data items separated by commas, creating a non-empty list

You can also use List () to create a list:

Returns an empty list when no arguments are specified

Returns a shallow copy of this parameter when using list as a parameter

Attempt to convert a given object to a list type when other parameters are in use

1.3.2 List Index and fragmentation

Grammar Description
LST[1] Reading a second element
Lst[-2] Reverse read; Read the penultimate element
Lst[1:] Intercepting elements
LST = [' 5 ', ' White ', ' dog '] print (

lst[1]) print (
lst[-2])
print (lst[1:]) [out

]
5
White
[5, ' White ', ' dog ']
1.3.3 List Method

In the following table, L is the list.

Grammar Description
L.append (x) Append data item x to the end of L
L.count (x) The number of times the statistic element x appears in L
L.extend (M)
L + M
Append an item of iterable m to the end of L
L.index (x, start, end) Returns the leftmost index position of a data item X in L (or start:end fragment of L), resulting in a ValueError exception if x is not found
L.insert (i, X) Insert element x at index position I
L.pop () Removes the rightmost data item and returns the value of the element
L.pop (i) Removes the data item at the L index position I and returns the value of the element
L.remove (x) Remove the leftmost data item X from L, if X is not found to produce ValueError exception
L.reverse () Reverse the L
L.sort (...) Sort L, as with the built-in sorted () function, to accept the optional key and reverse parameters
L = [5, ' Python ', (1,2), 5, ' Today ']
l.append (9)
print (' list append: ', L ')
print (' Number of occurrences of 5 in the list: ', L.count (5))

L.extend (' hello ')
print (' Items in Append iterator: ', L ')
print (' python ' leftmost index value: ', L.index (' Python '))

L.insert (1, ' Insert ')
print (' inserts at index position 1: ', L ')
Pop_item = L.pop ()
print (data item at end of L: ', Pop_item)
print (' The result of removing the end data item: ', L '

l.remove ((1,2))
print (list after removing (1,2): ', L '

l.reverse ()
print (' Inverted list: ', L)

[out]
list append: [5, ' Python ', (1, 2), 5, ' Today ', 9] The
number of 5 occurrences in the list: 2
append the items in the iterator: [5, ' Python ', (1, 2), 5, ' to Day ', 9, ' h ', ' e ', ' l ', ' l ', ' O ']
"python" leftmost index value: 1
at index position 1 insert: [5, ' Insert ', ' Python ', (1, 2), 5, ' Today ', 9, ' H ', ' e ', ' l ', ' l ', ' O ']
l end data item: O
remove End data item Result: [5, ' Insert ', ' Python ', (1, 2), 5, ' Today ', 9, ' h ', ' e ', ' l ', ' l ']
list after removing (1,2): [5, ' Insert ', ' Python ', 5, ' Today ', 9, ' h ', ' e ', ' l ', ' l ']
reverse list: [' l ', ' l ', ' e ', ' h ', ' ', ' ', ' ', ' ', ' ', ' ', ' , 5, ' python ', ' Insert ', 5]
1.3.4 split operator

Any iteration (list, tuple, etc.) data type can be split using the sequence split operator, that is, *. For two or more variables to the left of the assignment operator, one uses the * to boot, the data item is assigned to the variable, and all remaining data items are given to the variable with the asterisk.

*rest, last = [1, 2, 3, 4, 5]
print (A, rest, last) [out

]
1 [2, 3, 4] 5
1.3.5 Delete

Because the list is mutable, we can delete its data items.

Delete a single data item

# Delete a data item

L = [5, ' Python ', (1,2), 5, ' Today ']
del l[1]
print (' Use del delete one: ', l)

L = [5, ' Python ', (1,2), 5, ' Today ']
l.pop (1)
print (' Remove one with pop: ', L '

[out] use Del to delete an item:
[5, (1, 2), 5, ' today ']
use pop to delete an item: [5, (1, 2), 5, ' Today ']

Delete a fragment

# Delete Fragment

L = [5, ' Python ', (1,2), 5, ' Today ']
del L[1:3]
print (' Use del Delete fragment: ', L)

L = [5, ' Python ', (1,2), 5, ' Today ']
l[1:3] = []
print (' use [] Delete fragment: ', L '

[out]
use del Delete fragment: [5, 5, ' today ']
use [] to delete fragmentation: [5, 5 , ' Today ']

1.3.6 List Connotation

The list connotation is an expression and a loop that has an optional condition enclosed in square brackets to generate data items for the list, and you can use the criteria to filter out unwanted data items, either by using an expression or by using an attached condition. Common syntax: [expression for item in iterable] [expression to item in Iterable if condition]

In the absence of a list of connotations, we find all leap years between 1900-1940 and a half year, which may be written:

# Common way to find a leap year between 1900-1940 years
leaps = List () in. In
Range (1900, 1940):
    if (year%4 = = 0 and year%100!= 0) or (ye ar%400 = = 0):
        leaps.append (year)
print (leaps)

[out]
[1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936]

After learning the list connotation we can simplify the program:

# list connotation find a leap year between 1900-1940 years leaps = [annual for year in
Range (1900, 1940) if (year%4 = = 0 and year%100!= 0) or (year%400 = = 0)]
print (leaps)

[out]
[1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936]

The two methods are equivalent and get the same result. 2. Collection type

Set is also a composite data type that supports the member-relational operator (in), the object size calculation operator (len ()), and is also iterable. Python provides two built-in collection types: A mutable set type, a fixed frozenset type. When iterating, the collection type provides its data items in any order.

only objects that can be hashed can be added to the collection . All built-in fixed data types (such as float, frozenset, int, str, tuple) are hash-capable and can be added to the collection. Built-in mutable data types (such as dict, List, set) are not hashed and cannot be added to the collection. 2.1 Collection

A collection is an unordered combination of 0 or more object references. The set is mutable, so it is easy to add and remove data items, but because the items in them are unordered , there is no concept of index position, or fragmentation or step spacing. 2.1.1 The creation of a collection

Use Set () to create a collection that returns an empty collection when you use set as a parameter, when you return a lighter copy of the argument, try to convert the given object to a collection

each data item contained in the collection is unique -adding duplicate data items is not a problem, but it is meaningless. For example, the three sets generated below are the same: set (' Apple '), set (' Aple '), {' E ', ' P ', ' l ', ' a '}. In view of this, collections are often used to delete duplicate data items. For example, X is a list of strings, and after executing x=list (set (x)), each string in X is unique, and the order of storage is arbitrary. 2.1.2 Set method and operator

S, T is a set, X is a data item.

Grammar Description
S.add (x) Add X to S-if s does not already contain X
S.clear () Empty S
S.copy () Returns a shallow copy of S
S.difference (t)
S-t
Returns a new collection that contains all of the data items in s but not in t
S.difference_update (t)
S-=t
Remove every item in T but not in s
S.discard (x) If x is in S, remove X
S.intersection (t)
S&t
Returns a new collection that contains all data items that are both contained in S and T
S.intersection_update (t)
S&=t
So that s contains its own intersection with T.
S.isdisjoint (t) Returns true if S does not have the same entry as T
S.issubset (t)
S<=t
If S is the same as T, or S is a subset of T, returns true;
S.issupset (t)
S>=t
Returns true if S is the same as T, or S is a superset of T
S.pop () Returns and removes a random item in S, and if S is empty, it produces a keyerror
S.remove (x) Removing x from S, if s does not contain X, generates KEYERROR
S.symmetric_difference (t)
S^t
Returns a new collection that contains each data item in s and T, but does not contain data items that are also in both collections
S.symmetric_difference_update (t)
S^=t
So that s only contains the symmetry difference between itself and T.
S.union (t)
S|t
Returns a new collection that contains all the data items in the set S and data items in t that are not in s
S.update (t)
S|=t
Adds a data item not contained in each s in T to the set S
The connotation of 2.1.3 Set

In addition to invoking set () to create a collection, or to create a collection using the set literal, we can create a collection using the collection's connotations. The set connotation is an expression and a loop with optional conditions, supported syntax: {expression for item in Iterable} {expression for item in iterable if condition} 2.2 Solid Set Set

A fixed set refers to a collection that cannot be modified once it is created, and can only be created using the frozenset data type function, and Frozenset () returns an empty fixed collection with a frozenset parameter, which returns a shallow copy of the modified parameter. For any other type of argument, an attempt is to convert the given object to a forzenset. 3, mapping type

A map is a combination of key-value data items and provides methods for accessing data items and their keys and values. PYTHON3.0 supports two unordered mapping types-the built-in dict type and the collections.defaultdict type in the standard library. Python3.1 introduces a new and ordered mapping type collections. Ordereddict, the type is a dictionary, with the same methods and properties as the built-in dict, but in the insertion order when storing data items. 3.1 Dictionaries

Dict is an unordered combination of data types that contains 0 or more key-value pairs. the creation of the 3.1.1 dictionary

You can use {} to create an empty curly brace create an empty dictionary contains one or more comma-separated key-value pairs, creating a Non-empty Dictionary

You can also use the Dict () function to create an empty dictionary with a dict type parameter, to return the parameters of the combination of the light copy key value pairs of the parameter, and to create a non-empty dictionary

The dictionary's key values are unique , so if you add an existing key value entry to the dictionary, the actual effect is to replace the old value with the new value. 3.1.2 Dictionary Method

D for Dictionaries

Grammar Description
D.clear () Remove all items from D
D.copy () Returns a shallow copy of D
D.fromkeys (S, v) Returns a dict that has the key of the dictionary in sequence s, and the value is None or V
D.get (k) Returns the value associated with the key K and returns none if there is no k in D
D.get (k, v) Returns the value associated with the key K and returns v if there is no k in D
D.items () Returns the view of all (key, value) pairs in D
D.keys () Returns the view of all keys in D
D.pop (k) Returns the association value of the key K and removes the entry with the key K, which produces keyerror if K is not included in D
D.pop (k, v) Returns the association value of the key K and removes the entry with the key K and returns v if K is not included in D
D.popitem () Returns and removes any of the D (key, value) pairs if D is empty and generates KEYERROR
D.setdefault (k, v) As with the D.get () method, the difference is that if K is not included in D, a new entry with a key of K is inserted with a value of None or V
D.update (a) The key, which is not already contained in a in D, value is added to D, for each key that is contained in D and a, the corresponding value in a is substituted for the corresponding value in D--a can be a dictionary or a iterable or keyword parameter of (key, value) pair
D.values () Returns a view of all values for D

The view concept is mentioned above, which has two different points relative to the usual iterables: if the dictionary referenced by the view changes, the view will reflect the change. The key view and item view support some operations that are similar to collections:
V & x # intersection V | X # Union V-x # Difference v ^ x # symmentric Difference

Note: Comparison of two ways of using key values

We can use the d[k] and d.get () two forms to take values, such as when we do word frequency statistics, using words[word]+=1 or Words[word] = Words.get ( Word, 0) + 1 can add 1 operations, but if the first occurrence of the word, the first form will produce a keyvalue error, the second will run correctly. The connotation of 3.1.3 dictionary

The dictionary connotation is an expression and a loop with an optional condition. Syntax: {keyexpression:valueexpression for key, value in Iterable} {keyexpression:valueexpression for key, value in Iterable If condition}

Cases:

# Create dictionaries using dictionary connotations, where each key is the file name of the file in the current directory, and the value is a byte-counted folder size
import os
file_sizes = {name:os.path.getsize (name) for name in Os.listdir ('. ')}
Print (file_sizes)

[out]
{'. Ipynb_checkpoints ': 0, ' chapter III combination data type. IPYNB ': 12387}
3.2 Default Dictionary

The default dictionary is also a dictionary--the dictionary contains all the operators and methods provided by the ordinary dictionary, and, unlike the other, it can handle the missing keys .

When creating a default dictionary, we can pass in a factory function, which creates a default value for the missing key. Look at the example below

Import collections
words = collections.defaultdict (int)
x = words[' A ']
print (x)

[out]
0

The default dictionary words we created above never produces a keyerror exception, and if a key is not encountered, its value is set to 0 by the factory function (int ()). 3.3 ordered Dictionaries

Ordered dictionary collections. The ordereddict is stored in the order in which the data items are inserted.

Import Collections
D = collections. Ordereddict ([(' 1], (' second ', 2), (' Third ', 3)])
print (D.keys ())

[out]
odict_keys ([' A ', ' Second ', ' third '])

It can be seen that after we create an ordered dictionary from the two-tuple list, it is also ordered to get the key view.

An ordered dictionary another slightly more professional use is to generate a sort dictionary. Given a dictionary d, you can convert to a sort dictionary as follows: D=collections. Ordereddict (Sorted (D.items ())). 4. Iteration and replication of combined data types 4.1 iterations, iterative operations and functions

The Iterable data type returns one of the data items at a time. Any object that contains the __iter__ () method or any sequence (also the object containing the __getitem__ () method) is a iterable and can provide an iterator. An iterator is an object that can provide a __next__ () method that returns each successive item of data sequentially and produces a stopiteration exception when there are no data items.

Common iterative operators and functions (s and T are sequences):

Grammar Description
S+t Returns a sequence that is the connection between S and T
S*n Returns a sequence that is the connection of n copies of S
X in I Returns True if X appears in Iterable I
All (i) Returns true if each of the items in Iterable I evaluates to True
Any (i) Returns true if any of the items in Iterable I evaluates to True
Emumerate (i, start) Typically used in the for ... in loop, provides a sequence of (index, item) tuples in which the index actually has a value of 0 or start
Len (x) Returns the "Length" of X
Max (I, key) Returns the largest item in Iterable I, if given a key function, returns the maximum item value of the key (item)
Min (i, key) Returns the smallest item in iterable I, if given a key function, returns the minimum item value of the key (item)
Range (start, stop, step) Returns an integer iteration that uses a parameter (stop) to range from 0 to stop-1, with two parameters (start and stop), and the range of iterations from start to Stop-1, and three parameters when using the value of the Iteration substring range from start to stop-1, interval step between each two values
Reversed (i) Returns an iteration in which the iteration is reversed from the returned item in the Iteration child I
Sorted (I, key, reverse) Returns the items from the iteration sub-I in sorted order, key is used to provide DSU (cosmetic, sort, reverse-decorated) sort, and if reverse is true, the sort is sorted in reverse order
Sum (i, start) Returns the and of the items in Iterable I, plus start (default 0), I can contain strings
Zip (I1, ..., in) Returns the iteration of a tuple, using the iteration i1 to

The order in which data items are returned depends on the underlying iterable. For cases such as lists and tuples, the return value of the data item is usually returned from the first data item, and for dictionaries and collections, the iteration is a return item in any order. 4.2 Replication of combination types

Because a piece of data is always a separate copy of a piece of data, getting a copy of a list can be done in the following ways:

LST = [' Apple ', ' dog '

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.