Python - Strings and Common Data Structures

Posted by nikefido on Fri, 20 Sep 2019 13:45:11 +0200

Catalog

Preface: In this chapter, we study common storage structures such as strings, lists, tuples, dictionaries, etc.

1. string

A string is a finite sequence of zero or more characters. Simply put, the data in double or single quotation marks is a string.

Let's look at the use of strings through the following code

# -*- coding:utf-8 -*-
def main():
    str1 = 'hello world!'
    #Calculate the length of function string by len
    print(len(str1))
    #Get a capital copy of the first letter of the string
    print(str1.capitalize())
    #Get a full capitalized copy of the string
    print(str1.upper())
    #Query or Is Included in str1 Including Return Index Value
    print(str1.find("or"))
    #Query if and is included in str1
    print(str1.find("and"))
    #index is similar to find but cannot find an exception that will be thrown
    print(str1.index("or"))
    #print(str1.index("or"))
    #Check whether the string begins with the specified string
    print(str1.startswith("he"))
    print(str1.startswith("1he"))
    #Check whether the string ends with the specified string
    print(str1.endswith("!"))
    #Centralize the string with the specified width and add the specified characters on both sides
    print(str1.center(50,"*"))
    print(str1.rjust(50," "))
    str2 = "abc123456 ";
    # String Slicing: Extracting a character from a string at a specified location
    print("str2[2]: ",str2[2])
    print("str2[2:]:",str2[2:])
    print("str2[::2]:",str2[::2])
    print("str2[::-1]:",str2[::-1])
    print("str2[-3::-1]:",str2[-3::-1])
    # Check that strings are made up of numbers
    print(str2.isdigit())
    # Check that strings are composed of letters
    print(str2.isalpha())
    # Check that strings are composed of numeric letters
    print(str2.isalnum())
    #Remove bilateral blanks
    print(str2.strip())

if  __name__ == '__main__':
    main()

Output result

 

str = "helloworld"

Method Explain Result
len(str) String length 10
str.capitalize() Capitalization of string initials Helloworld
str.upper() Full capitalization of strings HELLOWORLD
str.find("or") Check if "or" is included in str, if it returns the initial index value, otherwise it returns - 1 6
str.startswith("h") Check whether the string begins with the specified string True
str.endswith("!") Check whether the string ends with the specified string False
str.center(20,"*") Centralize the string with the specified width and add the specified characters on both sides *****helloworld*****
str.isdigit() Check that strings are made up of numbers False
str.isalpha() Check that strings are composed of letters True
str.strip() Remove bilateral blanks helloworld

 

2. list

Lists are ordered, variable sequences built into Python. All elements of a list are placed in a pair of parentheses "[]" separated by commas.

List Common Methods

Method Explain
lst.append(x) Add element x to the end of list lst
lst.extend(L) Add all elements in List L to the end of List lst
lst.insert(index, x) Add element x to the list lst at the specified location index, and move all elements after that location back to one location
lst.remove(x) Delete the specified element that first appears in the list lst, and move all elements after that element forward by one position
lst.pop([index]) Delete and return the element labeled index (default - 1) in list lst
lst.clear() Delete all elements in list lst, but retain list objects
lst.index(x) Returns the subscript of the element whose first value is x in the list lst, and throws an exception if there is no element whose value is x
lst.count(x) Returns the number of occurrences of the specified element x in the list lst
lst.reverse() Inversely order all elements of list lst
lst.sort(key=None, reverse=False) Sort the elements in the list lst, key is used to specify the sorting basis, and reverse decides whether to False or True.
lst.copy() Shallow replication of return list lst

 

2.1 Addition, deletion and modification of list

def main():
    list1 = [1,3,5,7,100]
    print(list1)
    list2 = ['hello'] * 5
    print(list2)
    # Calculate the length of the list
    print("The length of the list is:",len(list2))
    #Subscript index
    print("Elements with index 0:",list1[0])
    print("Elements with index 3:",list1[3])
    print("Index is-1 Elements:",list1[-1])
    #Modifying elements
    list1[2] = 300
    print("Modification result:",list1)
    #Additive elements
    list1.append(121)
    print("append The result of adding elements:",list1)
    list1.insert(1,676);
    print("insert The result of inserting elements:",list1)
    list1 += [700,800]
    print("+=Additive elements:",list1)
    #Delete elements
    list1.remove(700)  #Remove an element
    print("remove Removing Elements:",list1)
    list1.pop();    #Remove the last element of the list
    print("pop Remove the last one",list1)
    del list1[0]    #Remove a subscript element
    print("del remove:",list1)
    list1.clear() #clear list
    print("Cleared list:",list1)


if __name__ == "__main__":
    main()

Output result

 

Slicing and sorting of 2.2 lists

1. Slicing of Lists

"""
//Slicing of lists
version:0.1
author:coke
"""
def main():
    names = ["A","B","C","D"]
    names += ["E","F","G"]
    # Loop through list elements
    for name in names:
        print(name,end = " ")
    print()
    # List slice
    names2 = names[1:4]
    print("names2:",names2)
    # Complete slicing operations can be used to copy lists
    names3 = names[:]
    print("names3:",names3)
    # Copies of inverted lists can be obtained by reverse slicing
    names4 = names[::-1]
    print("names4:",names4)

if __name__ == "__main__":
    main()

Output result

 

2. The sorting of lists

"""
//Sorting operation of list
version:0.1
author:coke
"""
def main():
    list1 = ["A","Be","C","D","E"]
    list2 = sorted(list1)
    print("list2:",list2)
    # The sorted function returns that the sorted copy of the list will not modify the incoming list
    list3 = sorted(list1,reverse=True)
    print("list3:",list3)
    # Specify sorting by string length instead of default alphabetical order by key keyword parameter
    list4 = sorted(list1,key=len)
    print("list4:",list4)

if __name__ == "__main__":
    main()

Output result

 

2.3 Generative Grammar

We can also use the generative syntax of lists to create lists.

"""
//Generate trial grammar to create lists
version:0.1
author:coke
"""
import sys
def main():
    f = [x for x in range(1,10)]
    print("f:",f)
    f = [ x + y for x in "ABCDE" for y in "1234567"]
    print("f:",f)
    #Creating List Containers through List Generating Expressions Syntax
    #After creating lists with this syntax, the elements are ready for all the memory-consuming space.
    f = [x ** 2 for x in range(1,1000)]
    print("Generative Trial Grammar:",sys.getsizeof(f)) #9024
    #print(f)
    #Note that the following code creates not a list but a generator object
    #Every generator object can get data, but it does not take up extra space to store data.
    #Every time you need data, you get it through internal operations.
    f = (x ** 2 for x in range(1,1000))
    print("Generator object:",sys.getsizeof(f))
    print(f)
    """
        for val in f:
        print(val)
    print(sys.getsizeof(f))
    """
if __name__ == "__main__":
    main()

Output result

 

In addition to the generator syntax mentioned above, Python has another way of defining generators, which is to transform a common function into a generator function by using the yield keyword. The following code demonstrates how to implement a generation Fibolachian sequence Generator. The so-called Fibolacci sequence can be passed through the following recursion Method to define:

"""
//Definition Generator
version:0.1
author:coke
"""
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()

 

3. tuple

Python tuples are similar to lists, except that elements of tuples cannot be modified. Tuples are bracketed and lists are bracketed.

def main():
   # Define tuple
   t = ('Luo Hao', 38, True, 'Chengdu, Sichuan')
   print(t)
   # Get elements in tuples
   print(t[0])
   print(t[3])
   # Traversing values in tuples
   for member in t:
       print(member)
   # Reassigning tuples
   # t[0] = 'Wang Da hammer'  # TypeError
   # Variable t refers back to the new tuple. The original tuple will be garbage collected.
   t = ('Wang Da hammer', 20, True, 'Kunming, Yunnan')
   print(t)
   # Converting tuples into lists
   person = list(t)
   print(person)
   # Lists can modify their elements
   person[0] = 'Bruce Lee'
   person[1] = 25
   print(person)
   # Converting lists to tuples
   fruits_list = ['apple', 'banana', 'orange']
   fruits_tuple = tuple(fruits_list)
   print(fruits_tuple)


if __name__ == '__main__':
   main()

Here's a very interesting question. We already have the data structure of lists. Why do we need tuples?

  1. Elements in tuples can't be modified. In fact, we're especially interested in projects. Multithreading The environment (which will be discussed later) may prefer to use invariant objects (on the one hand, because the state of the object can not be modified, so it can avoid unnecessary program errors caused by this, that is to say, an invariant object is easier to maintain than a variable object; on the other hand, because there is no one Threads can modify the internal state of invariant objects, and an invariant object is thread-safe automatically, so that the overhead of processing synchronization can be saved. An invariant object can be easily accessed by sharing. So the conclusion is: if you don't need to add, delete or modify elements, you can consider using tuples. Of course, if a method wants to return multiple values, using tuples is also a good choice.
  2. Tuples are superior to lists in terms of creation time and space.

 

4. set

The set in Python is consistent with the set in mathematics. No repetitive elements are allowed, and intersection, Union and difference sets can be performed.

"""
//Use set
version:0.1
author:coke
"""
def  main():
    set1 = {1,2,3,3,2,4}
    print(set1)
    # len() Finds the Length of the Set
    print('Length=',len(set1))
    set2 = set(range(1,10))
    print(set2)
    set1.add(7)
    set1.add(8)
    set2.update([11,12])
    print("set1:",set1)
    print("set2:",set2)
    # Remove element 5
    set2.discard(5)
    # The absence of remote elements causes keyError
    if 4 in set2:
        set2.remove(4)
    #Traversing Collection Containers
    for ele in set2:
        print(ele,end=" ")
    print(" ")
    #Converting tuples into collections
    set3 = set((1,2,3,4,5))
    print(set3.pop())
    print("set3:",set3)
    # Intersection, union, difference and symmetric difference of sets
    print("Intersection:",set1 & set2)
    print("Union:",set1 | set2)
    print("Difference sets:",set1 - set2)
    print("Symmetric difference operation:",set1 ^ set2)
    #Judgment subset and superset
    print("subset:",set1 <= set2)
    #print(set1.issuperset(set2))
    print("Superset:",set1 >= set2)
    #print(set1.issubset(set2))

if __name__ == "__main__":
    main()

Output result

 

5. dictionary

Dictionaries, like lists, can store multiple data. Each element of a dictionary consists of two parts: key: value. For example,'name':'squad leader','name'is the key and'squad leader' is the value.

5.1 Addition, deletion and revision of dictionaries

1. Adding Elements

info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia Beijing, China'}
# print('id by:%d'%info['id'])#The program runs on the terminal because it accesses keys that do not exist.
newId = input('Please enter a new student number:')
info['id'] = newId
print('After adding id by:',info['id'])

 

2. Modifying Elements

info = {'name':'Monitor', 'id':100, 'sex':'f', 'address':'Earth Asia, China, Beijing'}
newId = input('Please enter a new student number:')
info['id'] = int(newId)
print('After modification id For:',info['id'])

 

3. Delete elements

  • Delete the specified element
  • clear() empty the entire dictionary
info = {'name':'Monitor', 'sex':'f', 'address':'Earth Asia, China, Beijing'}
print("Before deleting:",info)
del info['name']
print('After deletion:',info)
info.clear()
print("After emptying:",info)

 

4. Find an element

When a dictionary queries an element, if the dictionary does not have the elements it queries, it will make an error, so it is better to judge before querying.

info = {'id':1,'name':'Monitor', 'sex':'f', 'address':'Earth Asia, China, Beijing'}
print("query:",info)
print("Query Existing Elements:",info['id'])
#print("Elements that do not exist in the query:", info ['age']) keyError
print("Query elements that do not exist:",info['age'] if 'age' in info else "Element does not exist")

 

Common operation of 5.2 dictionary

1. len(): Measure the number of key-value pairs in a dictionary

dict = {"name":"Jack","age":11}
print(len(dict))

 

2. keys(): Returns a list of all keys in the dictionary

dict = {"name":"Jack","age":11}
print(dict.keys())

 

3. values(): Returns a list of all values in the dictionary

dict = {"name":"Jack","age":11}
print(dict.values())

 

4. items(): Returns a list of all (key, value) tuples

dict = {"name":"Jack","age":11}
print(dict.items)

 

5. Dictionary traversal

"""
//Dictionary testing
version:0.1
author:coke
"""
info = {"name":"coke","age":11,"height":"198"}

print("Traversing dictionary items--------------------The first way")
for item in info.items():
    print(item)
print("Traversing dictionary items--------------------The second way")
for key,value in info.items():
    print("%s:%s"%(key,value))

Topics: Python