In Python, we often use lists, dictionaries and other data types to store data or reconstruct a sequence, and there are some relationships between them. Next, we will take a comprehensive look at several data types commonly used in Python.

The difference between

The same

  • It’s a container for storing data
  • You can use for… In for a loop

The difference between

Sequences hold different types of data, and iterators hold algorithms.

Sequence is to store the data in advance, and to get the data through the cycle or index; The iterator does not need to store the data, but obtains the next data through the algorithm.

Each piece of data in the sequence is allocated memory; The iterator doesn’t need to, it just computes the next value each time. From this point of view, iterators are more appropriate if you are processing large amounts of data.

Sequences can get a value by index or key name, whereas iterators can only use next() to get the next value.

Change trend

From left to right, you can try to find patterns.

From the sorting of the data, it can be seen from left to right that it is unordered, ordered, and regular (also can be defined as ordered).

In terms of the flexibility of data operation, the one on the left is more flexible and can be added, deleted, changed and checked. The right-hand side is relatively unitary and can only be queried (note: defined strings can only be queried; the string generated by the method is not the original string).

From the perspective of the symbols of custom data types, but also follow the characters of large – in – small – lead to implementation, such as dictionary | collection is curly braces, the list is brackets, yuan set of parentheses, string for double quotes or single quotation marks.

Conversion between data types

The above different data types can also be converted into each other. When converting, you only need to call corresponding functions, as shown in the following figure

The following figure shows an example of the interconversion between each data type.

As can be seen from the above table, data types can be transformed into each other, which can be summarized as follows:

  • No matter what data type is converted, the specific data type is surrounded by keywords, such as a tuple converted to a list: list(tuple)
  • When converting to a dictionary, note that two sets of data must be enclosed in parentheses, so that the dictionary can be generated correctly. If it is a single element, an error will be reported.
  • When converting to a string, note that although STR (data) can be converted to a string, in many cases this is not what you want. Instead, you want to combine the elements of a sequence into a string, which can be achieved using the join() method.

To convert to a dictionary, two elements must be combined into a tuple. For simplicity we can use zip() to form a new dictionary from the two sequences.

# Merge the two lists into a sequence using zip, which is then converted into a dictionary.
lst1 = ['x'.'y'.'z']            # can be a list, tuple, or collectionLst2 = [123234345]print(dict(zip(lst1,lst2)))         
# output:
{'x': 345, 'y': 234, 'z': 123}
Copy the code

The data transformed by STR () becomes a string, but we want to combine the elements of the sequence to make a string. You can then use the join() method to change its elements to the desired string.

# grammar:
    "sep".join(seq) 
# instances:
    x = "".join({'a': 123,'b': 345})print("x:",x)
    y = ",".join(['java'.'python'.'c++'])
    print("y:",y)
    z = "_".join(("tuple"."demo"."01"))
# output:
    x: ab
    y: java,python,c++
    z: tuple_demo_01
# description:Sep is the separator and seQ sequenceCopy the code

The convenient way to write it is to derive it

Some of the above data structures also support derivations, which are expressions that can be constructed from an iterable into a new iterable. Derivations can be used to quickly implement a new sequence or generator, and can also make code more elegant and fast.

To make it more intuitive, we can summarize the inferences supported by different data types in a diagram. We just have to remember 433.

Dictionary derivation

# grammar:
    {<operation_key:operation_value> for key,value in dict condition }
# instances:
    d = {'chinese': 88, 'math': 92, 'english': 93, 'history': 84}
    print("Subjects greater than 90:", {k: 'good' for k, v in d.items() if v >= 90})
# outputSubjects with scores greater than 90: {'math': 'good'.'english': 'good'}
# description:
    forAn expression after a loop can be a conditional expression or a loop expression, which is mainly used for filtering or nesting loops. The result is a new dictionary generated after an operation based on the expression.Copy the code

Set derivation:

# grammar:
    {<operation_key:x> for x in set condition }
Example #
    s = {x**2 for x in [1, 2, 3]}
    print("The collection" s.",s)
# output:Set S: {1, 4, 9}Copy the code

List derivation

# grammar:
    [ operation(x) for x in list condition ]
Example #
    print([random randint (1, 10) + xfor x inRange (0, 10)if x % 2 == 0])
# the results:
    [3, 3, 14, 15, 12]
# description:
    # Common uses of list comprehensionsUsage: [x]for x in iterable ]                  # Print directly after loopUsage 2: [xfor x in可迭代if condition(x) ]  # Conditional judgment of xUsage 3: [operation(x)for x iterable if condition(x)]  After judging the x condition, perform the operation on xUse 4: [operation (x, y)for x in可迭代for y in iterable1] # nested loop, execute x,y
Copy the code

Generator derivation

# grammar:
    ( operation(x) for x in iterable condition )
Example #
    print((random. Randint (1, 10) + xfor x inRange (0, 10)if x % 2 == 0))
# the results:
    <generator object <genexpr> at 0x02FDC420>
# description:The newly generated generator can be usedforLoop, or next() to get its next valueCopy the code

Combination usage

The above data structures can be used as containers or in combination for other purposes. For example, it can be used as a conditional statement. For intuition, let’s start with a simple if statement.

score = 92
if score >= 90:
    print('good')
else:
    print('good')
# Output: excellent
Copy the code

Next, we will redefine conditional statements in three ways.

First, use ()+[] to implement conditional judgment

# grammar:
    (<return_false>, <return_true>)[condition_expression]
# instances:
    score = 92
    print(('good'.'good')[ score >= 90 ])
# the results:good# description:Write conditional statements in [] and values that return true and false in (). () () () () () () () () () () () () () () (Copy the code

Second, use {}+[] to implement conditional judgment

# grammar:
    {True: <return_true>, False: <return_false>}[<condition_expression>]
# instances:
    score = 92
    print({True:'good',False:'good'}[ score >= 90 ])
# the results:good# description:Write conditional statements in [] and return true and false values in (), in orderCopy the code

The third way to evaluate strings is to use the eval method.

# grammar:
    eval("String judgment statement")
Example #
    print('good' if eval("score >= 90") else 'good')
# the resultsgoodCopy the code

This article is only for learning, copyright belongs to the original author, if there is infringement, please contact delete.

You will definitely encounter difficulties in learning Python. Don’t panic, I have a set of learning materials, including 40+ e-books, 800+ teaching videos, covering Python basics, crawlers, frameworks, data analysis, machine learning, etc. Shimo. Im/docs/JWCghr… Python Learning Materials

Follow the Python circle and get good articles delivered daily.