Python3 Combining data types (tuples, lists, collections, dictionaries) syntax

Source: Internet
Author: User

One, sequence type (string, tuple (), list [])

Sequence types support In,len (), Shard [], iteration, 5 built-in sequence types: bytearray,bytes,list,str,tuple (tuples).

1, tuples can be nested (such as: x=str[2][1][0][1])

2, the tuple name (Collections.namedtuple (), that is, the custom)

Sample: Sale=collctions.namedtuple ("Sale", "ProductID CustomerID Date Price") is the name of the tuple type before the comma, the argument after the comma is a string, separated by a space, Each name represents an entry for the tuple data type, such as: X=sale (121, "2017-03-22", 1,10.99), and a call to an item can be implemented using X.price, where the result is 10.99;

For formatted substitutions, the **namedtuple._asdict () function can be used to replace the index directly with the name, such as: "{productid}{price}". Format (**x._asdict ()). This method is good for multilayer tuples, and name is the name of the outermost tuple.

A tuple of a single element needs to be prefixed with a comma.

3. List

The 1> list can also store any type of data, and you can use comparison operators (to compare items by item) and modify the contents of the list.

The 2> list supports all operations of tuples, as well as the following functions:

Append () Append

COUNT (x) counts the number of occurrences of X

Index (x,start,end) to find X, if not, to produce a valueerror,

Extend () (equal to + =),

Insert (I,X) (inserts x at index position i),

Pop () Remove last item

Pop (i) (removes the data item at the I index position, if there is no I value, the last item is removed by default),

Remove (x) (removes the first item from the left that appears as X, and returns a valueerror if none).

Reverse () reversal,

Sort ().

Assigning a specific position to a sequence can be substituted and modified for a single data in a list (X[1]=2;x[1:2]=[a,b], the number of new items is not necessarily equal to the number of items in the original data, can be any number, the result is the replacement of the Shard of the selected shards, If the new replacement shard is empty, it is equivalent to deleting the original shard you have selected, Del X[1:2] can also play the effect of deleting the Shard (although del actually removes the binding between the data item and the variable).

3> using * to split a sequence to assign a value

Sample: a,*b,c=[1,2,3,4,5,6], a,b,c= (1, [2, 3, 4, 5], 6)

The data item is assigned by the variable by position, and all the remaining data is assigned to the variable with the * number. * The function is to split a iterable.

Another function of "*" is to copy the operator, which is equivalent to multiplication sign, but the object is not limited to numbers and can be any object.

4> list connotation (used to create some lists with a lot of data)

[Expression for item ' in iterable] (expression operation for each data item in iterable)

[Expression for item ' in iterable if condition], which operates on a qualified object.

Example: Leaps=[y for y in range (1900,2000) if (y%4==0 and y%100!=0) or (y%400==0)] calculates a leap year. (range is also closed before opening)

Multi-variable nesting of list connotations:

Example: Cods=[s+z+c for S in ' MF ' for z in ' SMLX ' for C in ' BGW '

The If not (s== "F" and z== "X")] is equivalent to a three-layer overlay for loop.

Ii. collection type (set) ({})

Set supports in, Len (), comparison, bitwise logical operators, and is also iterable. Only objects that can be hashed can be added to the collection. All built-in fixed data types (Float,frozenset,int,str,tupul ...) Are all hash-crunching. Built-in mutable data types (such as: Dict,list,set) are not hash-operated.

Creates a collection of available set ("A", "B", 3), and creates an empty collection that must be set (). When a collection is created, there can be two identical items, but it doesn't make sense, and the resulting collection will only hold one.

Example: S={2, "veil", ("a", 5), Frozenset ({8,4,7}), "a"}

Collections are not distinguished by index locations, nor can they be fragmented or partitioned by step distance. Each data in the collection is unique, so the collection is often used to delete duplicate data items (x=list (set (x))).

1, set common functions:

S.add (x) add X to the set S;

S.clear () empty;

S.pop () removes any item in the collection and returns a Keyerror exception if it is empty;

S.remove (x) removes the X item, which produces an keyerror exception if x does not exist;

S.discard (x) Remove the item if x exists;

S.copy () shallow copy; *

S.different (t) s-t returns a new collection that contains only s but not in the collection T;

S.difference_update (t) s-=t removes every item in the set T but not in s;

S.intersection (t) s&t returns the intersection of S and T;

2. Result of collection union operation operator:

S|t, S&t, intersection, S-t, minus the intersection with T, S^t, collection minus intersection.

3. Set connotation (same list connotation)

{expression for item in Iterable}

{expression for item in Iterable if condition}

4. Fixed set (Frozenset ())

Once created it is immutable, with static, available functions only those functions that do not change the contents of the collection itself (the * callout is already used).

Three, mapping type (DICT)

A map is an unordered combination of key-value data. The built-in mapping types are: Dict (), Collections.defaultdict (), and collections.ordereddict () for more than 3.1, which is the same as dict (), but has an index sequence.

A mapped key can only be used with a hash-only type, whereas a value can use any type of data.

1. Creation of dictionaries

D=dict (id=1948,name= "washer", size=3) #关键字参数

d={"id": 1948, "name": "Washer", "Size": 3} #面值

D=dict ({"id": 1948, "name": "Washer", "Size": 3}) #面值

D=dict ([("id", 1948), ("name", "washer"), ("Size", 3)]) #序列

D=dict (("id", "name", "Size"), (1948, "Washer", 3))) #序列

{} or use D=dict () to create an empty dictionary

2, using d["id"] will return the corresponding value, if this key does not exist, it will produce a keyerror.

d["XX"]=34 can add an item, and if this key already exists, the original value is modified.

Del d["XX"] deletes an item with the key "XX" and produces a keyerror if it does not exist.

3. Common functions (full)

D.clear () empty

D.copy () Shallow copy

D.pop (K,V) returns the value of K and deletes the K key, if K does not exist, returns Keyerror or V (if v exists)

D.popitem () removes any pair of key-values and generates KEYERROR if D is empty

D.values () Returns a view of all values in the dictionary

D.keys () Returns a view of all keys in the dictionary

D.items () Returns the view of all (key,value) pairs in the dictionary

D.get (k) returns the value of K and returns none if K does not exist

D.get (K,V) returns the value of K and returns v if K does not exist

D.setdefault (K,v) with Get (), if K does not exist insert a K term, the value is None or V (if V is given)

D.fromkeys (s,v) returns a dict whose key is the item of the sequence s, with a value of None or V (if V is given)

D.update (a) with a update d, if the key already exists, update the value, or insert if it does not exist. A can be a dict or a iterable (key,value) pair.

For

4, the iteration of the dictionary

Pair key: For key in D:print (key)

Or: For key in D.keys (): Print (key)

Pair value: For value in D.values (): Print (value)

Pair key-value: for Key,value in D.items (): Print (Key,value)

Or: For item in D.items (): Print (item[0],item[1])

5. The view of the dictionary key and the views of the item support some operations similar to collections (Union operation operations at the collection)

This can be used in to see if a key exists in dict, or if a union operation operation is available to see if the key for a particular collection exists in Dict, as follows:

D={}.fromkeys ("ABCD", 3); S=set ("ACX"); Matches=d.keys () &s #matches =={' A ', ' C '}

6. Dictionary connotation

{Keyexpression:valueexpression for key, value in Terable}

{Keyexpression:valueexpression for key, value in terable if condition}

Example: Key-value inversion for a dictionary: inverted_d={v:k for K, V in D.items ()}

7. Default dictionary (collectons.defaultdict ())

The default dictionary never produces Keyerror, and when the key of the query does not exist, the dictionary automatically generates a new key with this query key, whose value is the default value set when the dictionary was created.

Example: words=collections.defaultdict (int), the default value added to this dictionary is the number 0. The incoming int is a factory function (that is, a function without parentheses, with no parameters), which can be easily set up later with a lambda function.

8, ordered dictionary (collctions. Ordereddict ())

The data items of the dictionary are saved in the order in which they are inserted, and if an unordered dictionary is used to update (), the resulting results become unordered.

Do=collections. Odereddict ([(' Z ', 5), (3,6), (8, ' a ')]) or create an empty one and add one item at a time.

Converts an ordinary dictionary into an ordered dictionary: d=collections. Odereddict (Sorted (D.items ())).

Iv. iterative and replication of combined data

1. Common iterative operators and functions:

S+t two sequences of connections;

S*n returns the concatenated sequence of n s sequence;

X in S determines whether it is included, not in;

All (i) returns true if each item in Iterable I evaluates to true;

Any (i) returns true if any of the entries is true;

Enumerate (I,start) is typically used for for...in loops, providing a sequence of (Index,item) tuples where the index starting value is 0 or start; {Equivalent to dividing a sequence I into a single, and giving each serial number, using (Index,item), index to the automatically generated sequence number, item is the value of each item in turn)}

Len () returns the length;

Max (I,key) returns the largest item in Iterable I, and returns the item with the largest key (item) value given the key function.

Min (I,key) Ibid;

Range (Start,stop,step) returns a number iteration, left closed right, or 0 if not given start;

Reversed (i) reversal sequence;

Sorted (i,key,reverse) sort; reverse=true in reverse order. When key is present, it can be set to any function rule that you need, or even a function that you construct, such as key=abs in absolute order, key=str.lower, in the lower () function rule in Str. Sorted () sorting applies only to the combination types that all data items can be compared to each other, and generates a typeerror if there are different types.

SUM (i,start) sum, start is optional

The zip (i1,..., in) returns the iteration of the tuple, using the iteration i1 to In;i1-in, which are iterable data groups, for example, referring to the zip construction of dict. As long as the elements in one iterable are exhausted, the iterative process is terminated.

2, with A=iter (iterable structure) can get an iteration, in each loop with the next (a) method to obtain the next data item, when the end of a stopiteration exception will be generated.

3, the combination of data types of replication.

Sample: B= "Sudent", a=b such an equal sign is simply to assign the value of B to a, but the value of B "student" in the system has not been copied to 2 copies, only A and B are pointing to the "student" this value, whether it is from a or B to change the object "student", The other variable will also show the result after the change. To copy a copy of a "student", you can add the type name: A=str (b), or The Shard a=b[:] Because a copy is generated when the Shard is fetched. The copy () function is used for dictionary and collection types.

The above method is a shallow copy because it duplicates only the first layer of the object. If a mutable iterable object exists in the object, it copies only the reference address of the Iterable object, and if iterable changes from the original object, the iterable part of the copied object is changed. such as a nested list: [' A ', [' B ', ' C ']], copy this object [' B ', ' C '] part only to copy a reference address.       If you want to make a full copy of this object, you need to deep copy, import copy; A=copy.deepcopy (b)

4, the position constant naming general method: Water,tree,money=range (1,4); then the three-character values are, in turn, three-way

Python3 Combining data types (tuples, lists, collections, dictionaries) syntax

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.