Python strings and common data structures

Strings and common data structures

Use string

We can use the following code to understand the use of strings.


if __name__ == '__main__':
    main()

Python strings and common data structures

In addition to the string, Python also built a plurality of types of data structures, and if the operation to save the data in the program, most of the time can use existing data structure to achieve, including a list of the most commonly used, tuple, set, and dictionary.

Use the list

The following code demonstrates how to define a list, use the index to access a list of elements as well as add and delete elements.

main DEF ():
    List1 = [. 1,. 3,. 5,. 7, 100]
    Print (List1)
    List2 = [ 'Hello']. 5 *
    Print (List2)
    # calculates list length (number of elements)
    Print (len (List1) )
    # subscript (index) calculation
    Print (List1 [0])
    Print (List1 [. 4])
    # Print (List1 [. 5]) # IndexError: List OUT index of Range
    Print (List1 [-1])
    Print (List1 [ -3])
    List1 [2] = 300
    Print (List1)
    # additive element
    list1.append (200 is)
    list1.insert (. 1, 400)
    List1 + = [1000, 2000]
    Print (List1)
    Print (len (List1))
    # delete elements
    list1.remove (3)
    IF 1234 in List1:
        list1.remove (1234)
    List1 del [0]
    Print (List1)
    # empty list elements
    List1.Clear ()
    Print (List1)


if __name__ == '__main__':
    main()

Python strings and common data structures

And like strings, lists slicing operation may be done, we can achieve copy list by slicing operation or taken out of the part of the list to create a new list, the code shown below.

DEF main ():
    Fruits = [ 'Grape', 'Apple', 'Strawberry', 'at Waxberry']
    Fruits + = [ 'Pitaya', 'PEAR', 'Mango']
    # loops through the list of elements
    for fruit in fruits:
        Print (fruit.title (), End = '')
    Print ()
    # list slice
    fruits2 Fruits = [1: 4]
    Print (fruits2)
    # # fruit3 = Fruits not only created a new copy of the list of references
    # can complete slice operation to copy the list
    fruits3 Fruits = [:]
    Print (fruits3)
    fruits4 = Fruits [-3: -1]
    Print (fruits4)
    # list may be obtained by reversing the inverted copy slicing
    fruits5 = fruits [:: - . 1]
    Print (fruits5)


if __name__ == '__main__':
    main()

The following code implements a sort operation on the list.

main DEF ():
    List1 = [ 'Orange', 'Apple', 'Zoo', 'Internationalization', 'Blueberry']
    List2 the sorted = (List1)
    Copies # sorted function returns a list sorted list does not modify the incoming
    design # sorted as a function of the function should not produce side effects as possible
    list3 = sorted (List1, Reverse = True)
    # specified sort order, rather than by default alphabet key according to a keyword parameter string length
    list4 = sorted (list1 , Key = len)
    Print (List1)
    Print (List2)
    Print (list3)
    Print (list4)
    # message sent to the sorted list of objects sorted list of objects directly on
    list1.sort (Reverse = True)
    Print (List1)


if __name__ == '__main__':
    main()

We can also use the list to generate syntax to create the list, the code shown below.

Import SYS
 
DEF main ():
    F = [X for X in Range (. 1, 10)]
    Print (F)
    F = [X + Y for X in 'ABCDE' for Y in '1234567']
    Print (F)
    # with expression syntax to generate the list to create a list of vessels
    # after using this syntax to create a list of elements is ready so takes more memory space
    f = [the X-** for the X-2 in the Range (1, 1000)]
    Print (SYS. getsizeof (f)) # View the number of bytes of memory occupied by objects
    Print (f)
    # Please note that the following code creates is not a list but a generator object
    # can get to the data generator but it does not take up extra space storing data
    # each time the data is needed on the data obtained through the internal operation (it takes extra time)
    F = (X 2 for X in Range ** (. 1, 1000))
    Print (sys.getsizeof (F)) # compared formula builder does not occupy space for storing data
    Print (F)
    for Val in F:
        Print (Val)
 
 
IF the __name__ == '__main__':
    main ()

In addition to generating the above-mentioned syntax, Python there is another way to define the generator, is through the yield keyword transformed into a common function generator function. The following code demonstrates how to implement a generation generator Feibolaqie sequence. Feibolaqie may be called the number of columns defined by the following recursive method:

$${\displaystyle F_{0}=0}$$

$${\displaystyle F_{1}=1}$$

$${\displaystyle F{n}=F{n-1}+F_{n-2}}({n}\geq{2})$$

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
        yield a
 
 
def main():
    for val in fib(20):
        print(val)
 
 
if __name__ == '__main__':
    main()

Tuple

Python tuple is similar to the list, except that the elements of the tuple can not be changed in the previous code we've used more than once a tuple. As the name suggests, we have multiple elements combined together to form a tuple, so it can be saved as a list of pieces of data. The following code demonstrates how to define and use a tuple.

DEF main ():
    # define the tuple
    t = ( 'Luo Hao', 38, True, 'Chengdu')
    Print (T)
    # Get tuple in
    Print (T [0])
    Print (T [. 3] )
    # traversing tuple values
    for Member in t:
        Print (Member)
    # back to the tuple assignment
    # t [0] = 'King sledgehammer' # TypeError
    # variable t refer back to a new tuple original tuples will be garbage collection
    t = ( 'King sledgehammer', 20, True, 'Kunming')
    Print (T)
    # convert tuple to list
    Person = list (T)
    Print (Person)
    # listing can modify its elements
    person [ 0] = 'Bruce Lee'
    Person [. 1] = 25
    Print (Person)
    # converted into a tuple list
    fruits_list = [ 'apple', ' banana', 'orange']
    fruits_tuple = tuple(fruits_list)
    print(fruits_tuple)
 
 
if __name__ == '__main__':
    main()

Python strings and common data structures

Here's a question worth exploring, we have a list of such data structure, why do we need such a tuple type it?

1. tuple elements can not be modified, in fact, we especially multi-threaded environment (will be mentioned later) may prefer to use are those immutable objects (objects on the one hand because the state can not be modified in the project, so thus avoid unnecessary procedural errors caused, simply means that a constant than a variable target object easier to maintain; on the other hand because no one thread can modify the internal state of the same object, not a variable objects are automatically thread-safe, so you can save processing synchronization overhead. a constant object can be easily shared access). So the conclusion is this: If the elements do not need to add, delete, modify, they can consider using tuples, of course, if a method to return multiple values, use a tuple is a good choice.

Python strings and common data structures

Use collection

Python is a collection with a set of mathematical is the same, it does not allow duplicate elements but may be an intersection, union, difference and other operations.

 

 DEF main ():
    setl = {. 1, 2,. 3,. 3,. 3, 2}
    Print (setl)
    Print ( 'the Length =', len (setl))
    SET2 = SET (Range (. 1, 10))
    Print (SET2 )
    set1.add (. 4)
    set1.add (. 5)
    set2.update ([. 11, 12 is])
    Print (setl)
    Print (SET2)
    set2.discard (. 5)
    # Remove element if not present will lead to a KeyError
    IF. 4 in SET2:
        set2.remove (. 4)
    Print (SET2)
    # through the collection vessel
    for elem in SET2:
        Print (2 ** elem, End = '')
    Print ()
    # is converted into a set of tuples
    set3 = set ((1, 2,. 3,. 3, 2,. 1))
    Print (set3.pop ())
    Print (SET3)
    # set intersection and union, difference, symmetric difference operation
    print(set1 & set2)
    # print(set1.intersection(set2))
    print(set1 | set2)
    # print(set1.union(set2))
    print(set1 - set2)
    # print(set1.difference(set2))
    print(set1 ^ set2)
    # print(set1.symmetric_difference(set2))
    # 判断子集和超集
    print(set2 <= set1)
    # print(set2.issubset(set1))
    print(set3 <= set1)
    # print(set3.issubset(set1))
    print(set1 >= set2)
    # print(set1.issuperset(set2))
    print(set1 >= set3)
    # print(set1.issuperset(set3))
 
 
if __name__ == '__main__':
    main()

Description: Python allowed in some special way to custom operators (will be mentioned later chapters) of a certain type or data structure, when the above code, we set of methods for computing a set of objects can be called, can directly use the corresponding operators, operator & e.g. intersection with the method of action is the same, but use the operator make the code more intuitive.

Use a dictionary

Dictionary is another variable container model, similar to the dictionary used in our lives, it can store any type of object, and a list of different sets, each element of the dictionary are composed of a key and a value of " key-value pair "key and value separated by a colon. The following code demonstrates how to define and use a dictionary.

DEF main ():
    Scores = { 'Luo Hao': 95 'Baiyuan Fang': 78 'DiRenJie': 82}
    # can obtain the value of the dictionary corresponding through the key
    print (scores [ 'Luo Hao'])
    Print (Scores [ 'DiRenJie'])
    # dictionary traversal (traversal key and then the key is actually taken by the corresponding value)
    for elem in Scores:
        Print ( '% S \ T ---> \ T D%'% (elem, scores [elem]))
    elements in the dictionary update #
    Scores [ 'Baiyuan Fang'] = 65
    Scores [ 'ZHUGE wanglang'] = 71 is
    scores.update (cold = 67, 85 Fangqi He =)
    Print (Scores)
    IF 'Wu' Scores in:
        Print (Scores [ 'Wu'])
    print (scores.get ( 'Wu'))
    # GET method is obtained by a value corresponding to the key values but may set the default
    print (scores.get ( 'Wu', 60) )
    # remove an element dictionary
    print (scores.popitem())
    print(scores.popitem())
    print (scores.pop ( 'Luo Hao', 100))
    # empty dictionary
    scores.clear ()
    Print (Scores)
 
 
IF the __name__ == '__main__':
    main ()

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160794.htm
Recommended