Python implements a list inversion instance summary

  • 2020-04-02 14:22:32
  • OfStack

This example summarizes Python's approach to implementing list inversion. Share with you for your reference. The specific implementation method is as follows:

Here are a few different functions implemented

import math
 
def resv(li):
    new = []
    if li:
        cnt = len(li)
        for i in range(cnt):
            new.append(li[cnt-i-1])
    return new
 
def resv2(li):
    li.reverse()
    return li
 
def resv3(li):
    hcnt = int(math.floor(len(li)/2))
    tmp = 0
    for i in range(hcnt):
        tmp = li[i]
        li[i] = li[-(i+1)]
        li[-(i+1)] = tmp
    return li
 
li = [1, 2, 3, 4, 5]
 
print resv(li)

The ps: resv2() method changes the order of the original list, but the others do not
Some basic usage of list
1. The definition list
    >>> li = ["a", "b", "mpilgrim", "z", "example"]
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[0]                                     
    'a'
    >>> li[4]                                     
    'example'

 
2. Negative list index
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[-1]
    'example'
    >>> li[-3]
    'mpilgrim'
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li[1:3]
    ['b', 'mpilgrim']
    >>> li[1:-1]
    ['b', 'mpilgrim', 'z']
    >>> li[0:3]
    ['a', 'b', 'mpilgrim']

 
Add elements to the list
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example']
    >>> li.append("new")             
    >>> li
    ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
    >>> li.insert(2, "new")          
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
    >>> li.extend(["two", "elements"])
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

 
4. The search list
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.index("example")
    5
    >>> li.index("new")   
    2
    >>> li.index("c")     
    Traceback (innermost last):
      File "<interactive input>", line 1, in ?
    ValueError: list.index(x): x not in list
    >>> "c" in li         
    False

 
5. Remove the element from the list
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>> li.remove("z") 
    >>> li
    ['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
    >>> li.remove("new")
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']
    >>> li.remove("c") 
    Traceback (innermost last):
      File "<interactive input>", line 1, in ?
    ValueError: list.remove(x): x not in list
    >>> li.pop()       
    'elements'
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']

The first occurrence of removing a value from a list.
Remove simply removes the first occurrence of a value. Here, 'new' appears twice in the list, but li.remove("new") only removes the first occurrence of 'new'.
If no value is found in the list, Python throws an exception in response to the index method.
Pop does two things: delete the last element of the list, and then return the value of the deleted element.

6. List operator

    >>> li = ['a', 'b', 'mpilgrim']
    >>> li = li + ['example', 'new']
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new']
    >>> li += ['two']              
    >>> li
    ['a', 'b', 'mpilgrim', 'example', 'new', 'two']
    >>> li = [1, 2] * 3            
    >>> li
    [1, 2, 1, 2, 1, 2]

 
7. Join the list to make it a string
    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()])
    'server=mpilgrim;uid=sa;database=master;pwd=secret'

A join can only be used for a list where the element is a string; It does not do any type casts. Concatenating a list with one or more non-string elements throws an exception.

8. Split the string

    >>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> s = ";".join(li)
    >>> s
    'server=mpilgrim;uid=sa;database=master;pwd=secret'
    >>> s.split(";")  
    ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    >>> s.split(";", 1)
    ['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

A split, as opposed to a join, splits a string into a list of multiple elements.
Note that the separator ("; ") ) is completely removed and does not appear in any element of the returned list.
Split takes an optional second parameter, which is the number of times to split.

9. Map resolution of list

    >>> li = [1, 9, 8, 4]
    >>> [elem*2 for elem in li]    
    [2, 18, 16, 8]
    >>> li                         
    [1, 9, 8, 4]
    >>> li = [elem*2 for elem in li]
    >>> li
    [2, 18, 16, 8]

 
Parsing in dictionary
    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> params.keys() 
    ['server', 'uid', 'database', 'pwd']
    >>> params.values()
    ['mpilgrim', 'sa', 'master', 'secret']
    >>> params.items()
    [('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]
    >>> [k for k, v in params.items()]              
    ['server', 'uid', 'database', 'pwd']
    >>> [v for k, v in params.items()]              
    ['mpilgrim', 'sa', 'master', 'secret']
    >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

 
11. List filtering
    >>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
    >>> [elem for elem in li if len(elem) > 1]     
    ['mpilgrim', 'foo']
    >>> [elem for elem in li if elem != "b"]       
    ['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
    >>> [elem for elem in li if li.count(elem) == 1]
    ['a', 'mpilgrim', 'foo', 'c']

I hope this article has helped you with your Python programming.


Related articles: