Python list, meta-ancestor

Posted by fishown on Sat, 11 May 2019 20:02:05 +0200

Part of the content is compiled from Python, Little Turtle

List: An array of hormones
The concept of arrays is to put a large number of data of the same type together one by one, and then indexed by array subscripts. But the basic requirement of arrays is that the data you put together must be of the same type. Because Python variables have no data types, that is to say, Python has no arrays. But Python added a more powerful list.

  • Create list
    Creating lists is the same as creating ordinary variables. A pile of data is enclosed in middle brackets and separated by commas. Such a common list is created successfully.
>>> number = [1, 2, 3, 4, 5]
>>> list1 = [1, "kugua", 3.14, [1, 2, 3]]
>>> empty = []  #Create an empty list

It's not unreasonable to say that an array is a list of hormones. You can create a mixed list of fish and dragons. The list can be integer, string, floating point, or even contain another list. If you really don't know what data to put in the list, you can create an empty list.

  • Small Partners in the List
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', 
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 
'remove', 'reverse', 'sort']
  • Add elements to the list
    The append() method is used to append an element to the list, and multiple elements will report errors.
    The extend() method extends one list to another, so its parameters are a list.
    The insert() method can insert elements anywhere in the list. The insert() method has two parameters: the first parameter represents the location in the list, and the second parameter is an element inserted at that location.
>>> number = [1, 2, 3, 4, 5]
>>> number.append(6)  #Append element "6" to the end of the list
>>> number
[1, 2, 3, 4, 5, 6]

>>> number.extend([7, 8])
>>> number
[1, 2, 3, 4, 5, 6, 7, 8]
>>> number.insert(1,0)
[1, 0,2, 3, 4, 5, 6, 7, 8]
>>> number.insert(0, 0)  #Insert element "0" at the beginning of the list
[0,1, 0,2, 3, 4, 5, 6, 7, 8]
  • Get elements from the list

As with arrays, you can retrieve a single element from the list by its index value. Note that the list index value starts at 0:

>>> name =["Egg","Duck's egg","Goose egg","son of a bitch"]
>>> name[0]
'Egg'
>>> name[3]
'son of a bitch'

According to this method, the position of "dog's eggs" and "duck's eggs" can be adjusted.

>>> name[1],name[3] = name[3],name[1]
>>> name
['Egg', 'son of a bitch', 'Goose egg', 'Duck's egg']
  • Delete elements from the list

The remove() method removes elements from the list (given content)
del statement deletes an element of the list (given index), deletes the entire list, and slices
The clear() method clears the list

>>> name = ["Egg", "son of a bitch", "Goose egg", "Duck's egg"]
>>> name.remove("son of a bitch")  #Remove elements from the list
>>> name
['Egg', 'Goose egg', 'Duck's egg']

>>> del name[2:]
>>> name
['Egg', 'Goose egg']
>>> name.clear()
>>> name
[]

>>> name = ['Egg', 'Goose egg', 'Duck's egg']
>>> del name[1] 
>>> name
['Egg', 'Duck's egg']

>>> del name  #Delete the entire list
>>> name
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    name
NameError: name 'name' is not defined

The pop() method defaults to the last element in the pop-up list.
When an index value is added as a parameter, the corresponding element of the index value is popped up.

>>> name = ["Egg", "son of a bitch", "Goose egg", "Duck's egg"]
>>> name.pop()
'Duck's egg'
>>> name.pop()
'Goose egg'
>>> name
['Egg', 'son of a bitch']


>>> name = ["Egg", "son of a bitch", "Goose egg", "Duck's egg"]
>>> name.pop(2)  #The element with index 2 in the pop-up list (third element)
'Goose egg'
>>> name
['Egg', 'son of a bitch', 'Duck's egg']

- Other Common Small Partners

  • The count () method is used to calculate the number of times its parameters appear in the list
  • The index() method returns the position of its parameters in the list. index() has three parameters. The first one is the parameter to be looked up. The last two parameters are used to limit the scope of parameter search.
  • The copy() method can be used to copy a list (deep copy)
>>> list1 = [1, 1, 2, 3, 5, 8, 13, 21]
>>> list1.count(1)
2
>>> list1.index(1)
0

#Find the location of the second target in list1
>>> start = list1.index(1) + 1
>>> stop = len(list1)
>>> list1.index(1, start, stop)
1
  • The reverse() method flips the entire list in place.
>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list1.reverse()  
>>> list1
[8, 7, 6, 5, 4, 3, 2, 1]
  • The sort() method is to sort the members of the list in a specified way. By default, no parameters are required and the list is sorted from small to large. sort(func, key, reverse)
    func: algorithm key: keyword
    Reverse: The default value sort(reverse=False) denotes reverse order. If you want to sort from large to small, you can reassign reverse to True.
>>> list1 = [8, 9, 3, 5, 2, 6, 10, 1, 0]
>>> list1.sort()
>>> list1
[0, 1, 2, 3, 5, 6, 8, 9, 10]

>>> list1 = [8, 9, 3, 5, 2, 6, 10, 1, 0]
>>> list1.sort(reverse =  True)   #Specify the way to sort in reverse order (from large to small)
>>> list1
[10, 9, 8, 6, 5, 3, 2, 1, 0]

List slicing: [Start: End: Step] The elements at the beginning of the list slice are included, and those at the end are not. Using list fragmentation, we get a copy of the original list, the original list has not changed.

>>> name = ["Egg", "son of a bitch", "Goose egg", "Duck's egg"]
>>> name[0:2]      #Take the first two elements
['Egg', 'son of a bitch']
>>> name[:2]       #Take the first two elements
['Egg', 'son of a bitch']
>>> name[1:]       #Take the first element to the end
['son of a bitch', 'Goose egg', 'Duck's egg'] 
>>> name[:]      #Copy a list
['Egg', 'son of a bitch', 'Goose egg', 'Duck's egg']

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list1[0:9:2]     #A new list is composed of two elements in step size
[1, 3, 5, 7, 9]

>>> list1[::-1]      #Step size is set to - 1, which is equivalent to copying an inverted list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
  • List Copy Concept Supplement
    As mentioned above, using fragmentation to create a list of copies:
>>> list1 = [1, 3, 2, 9, 7, 8]
>>> list2 = list1[:]   #Copy list
>>> list2
[1, 3, 2, 9, 7, 8]

>>> list3 = list1   #Give [1, 3, 2, 9, 7, 8] another name in the storage space called list 3
>>> list3
[1, 3, 2, 9, 7, 8]

Make the following modifications by using the small partners in the list. Let's see the difference.

>>> list1.sort()
>>> list1
[1, 2, 3, 7, 8, 9]
>>> list2
[1, 3, 2, 9, 7, 8]
>>> list3   #And follow suit.
[1, 2, 3, 7, 8, 9]

I don't know if you remember the contents of the previous variables. Python variables are like a label, just a name. Look at the picture below.

Now you should understand that the way to specify a name for a list is to add a new label to the list. The real copy is to use the method of fragmentation. This is also the most confusing place for beginners, you must pay attention to writing code in the future.

  • List Derivation Formula (List Resolution)
    List comprehensions, also known as list resolution, are inspired by Haskell, a functional programming language. Ta is a very useful and flexible tool for creating lists dynamically.
    [The expression of A for A in B]
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> [i**2 for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

#The list generator above corresponds to:
>>> list1 = []
>>> for x in range(10):
	list1.append(x)
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

- Some common operators

  • Lists can also compare sizes (the first character of the first element of the list ASIIC code, and the next one is equal)
  • You can use the plus sign (+) to stitch characters, and the (*) sign to copy itself several times.
  • Compound assignment operators can also be used for lists
  • Membership operators in and not in (only one level of membership can be judged, if you need to determine the elements in the list, you should first enter a layer of list)
>>> list1 = [123]
>>> list2 = [234]
>>> list1 > list2
False

>>> list1 = [123, 456]
>>> list2 = [234, 123]
>>> list3 = list1 + list2
>>> list3
[123, 456, 234, 123]

>>> list1 = [123]
>>> list1 *=3
>>> list1
[123, 123, 123]

>>> list1 = ["Piglet", "kitten", ["Little fish","Little bird"],"puppy"]
>>> "kitten" in list1
True
>>> "Lesser panda" not in list1
True
>>> "Little fish" not in list1
True
>>> "Little fish" not in list1[2]
False

2. Yuan Zu: A list with shackles on it
The biggest difference between meta-ancestors and lists is that you can arbitrarily modify the elements in the list, insert or delete an element at will, but not for meta-ancestors, meta-ancestors can not be changed (like strings), so you can't expect meta-ancestors in-situ sorting and other advanced operations.
ps: The contents of the list in the meta-ancestor can be modified.

  • Create and access a meta-ancestor
    The middle parentheses are used to create lists, while the parentheses are mostly used to create meta-ancestors.
>>> tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8)

The way to access meta-ancestors is the same as lists. Fragmentation can also be used to replicate a meta-ancestor:

>>> tuple1[1]
2
>>> tuple1[5:]
(6, 7, 8)
>>> tuple1[:5]
(1, 2, 3, 4, 5)

>>> tuple2 = tuple1[:]
>>> tuple2
(1, 2, 3, 4, 5, 6, 7, 8)
  • The symbol of the list is the middle bracket ([]), while the symbol of the meta-ancestor is the comma (,), not the bracket ():
>>> temp = (1)
>>> type(temp)
<class 'int'>
>>> temp = 1, 2, 3
>>> type(temp)
<class 'tuple'>

Create an empty ancestor, just use parentheses; if the ancestor has only one element, add a comma (,) after it so that you can tell Python exactly what you want is a meta-ancestor, and don't fool you with any integer or floating-point type.

>>> temp = ()
>>> type(temp)
<class 'tuple'>
>>> temp = (1,)
>>> type(temp)
<class 'tuple'>

>>> 8 * (8)  
64
>>> 8 * (8,)   #Commas play a decisive role.
(8, 8, 8, 8, 8, 8, 8, 8)
  • Update and delete lists
    Like strings, a new string can be updated by copying existing fragments of strings, and the same method is used for Yuanzu: (the civet cat replaces the prince and makes the variable point to a newly constructed Yuanzu to update).
>>> temp = ("Little fish", "Little bird", "puppy")
>>> temp = temp[:2] + ("Gon Freecss",) + temp[2:]
>>> temp
('Little fish', 'Little bird', 'Gon Freecss', 'puppy')

#Indirect deletion of elements in meta-ancestors
>>> temp = temp[:2] + temp[3:]
>>> temp
('Little fish', 'Little bird', 'puppy')
>>> del temp
>>> temp
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    temp
NameError: name 'temp' is not defined

Homework:
1. Find the elements in the list li and remove the spaces for each element.
And find all the elements that start with'A'or'a' and end with'c',
And add it to a new list, and print the new list in the last loop.
li = ['taibai ','alexC','AbC ','egon',' Ritian',' Wusir',' aqc']

#Method 1
li = ['taibai ','alexC','AbC ','egon',' Ritian',' Wusir','  aqc']   jiexin
b = []

for ls in li:
    ls = ls.strip()
    if (ls.startswith("A") or ls.startswith("a")) and ls.endswith('c'):
        b.append(ls)
print(b)

#Method two
for i in li:
    s=i.strip()
    if s[0].upper() == 'A' and s[-1] == 'c':
        b.append(s)
for x in b:
    print(x)

2.
Develop a sensitive word filter program to prompt the user to enter comments if the user's input contains special characters:
The list of sensitive words Li = ["Python," "Java," "c", "PHP"]
Substitute *** for sensitive words in user input and add them to a list.
If the content entered by the user has no sensitive vocabulary, it is added directly to the list above.

li = ["Python,"Java,"c#","PHP"]
new_list = []
mes = input("Please make your coment:")
for each_invid_name in li:    #For every sensitive word
    if each_invid_name in mes:     #If the sensitive word is included in the user comment
        length = len(each_invid_name)
        mes = mes.replace(each_invid_name, "*" * length)    #Substitution of Sensitive Words
new_list.append(mes)
print(new_list)

Topics: Python Java PHP Programming