Tag:Python基础 列表 元组
Category:Python基础
Article From:https://www.cnblogs.com/xingyi-qjl/p/9122951.html

 Navigation in this section:

  • List list: increase    Delete    check    change    Other    The loop of the list

  • Tuple tuple


One, List list

list (listThe table isPython UsedPython data type. list[]00, the second index is1-1, and so on.

List listname  to demonstrate:

name = ["Madonna", "Cory", "Annie", "Nelly"]

   Now that we have Figurine out the specific location of the list elements and also set up a simple list, let’s know in detail what are the ways to get down to the list.

“Increase “When you add elements to a single list, you can’t insert elements in batches in a single way.append() and insert() two methods.append() insert() is the insert (add) element in front of the added index; when it is involved in two or more lists, the built-in method of the list also provides one.extend()

name = ["Madonna", "Cory", "Annie", "Nelly"]        #Create a list of class lists name

name.append("Eleanor")          #Add "Eleanor" at the end of the name list
print(name)                     #['Madonna', 'Cory', 'Annie', 'Nelly', 'Eleanor']

name.insert(1, "Baade")         #Add "Baade" before the element that is originally quoted as 1, that is, "Baade" occupies the place where the index was originally 1.
print(name)                     #['Madonna', 'Baade', 'Cory', 'Annie', 'Nelly', 'Eleanor']

b = [1, 2, 3]                   #Create a new list B
name.extend(b)                  #Add the entire B list to the name list
print(name)                     #['Madonna', 'Baade', 'Cory', 'Annie', 'Nelly', 'Eleanor', 1, 2, 3]

    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -> None -- append object to end """
        pass

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
        pass

append() insert() extend() Partial source code

“Delete:Pythonremove()ValueError error;pop()IndexError error;clear(): direct emptying list;del

name = ["Madonna", "Cory", "Annie", "Nelly", "Cory"]        #Create a list of class lists name
name.remove("Cory")             #Remove the first "Cory" element from the left
print(name)                     #['Madonna', 'Annie', 'Nelly', 'Cory']

name = ["Madonna", "Cory", "Annie", "Nelly", "Cory"]
name.pop()                      #The last element of the default delete list
print(name)                     #['Madonna', 'Cory', 'Annie', 'Nelly']
name.pop(0)                     #Specifies the first element in the delete list, which is equivalent to del.
print(name)                     #['Cory', 'Annie', 'Nelly']

name = ["Madonna", "Cory", "Annie", "Nelly", "Cory"]
del name[2]                     # Deleting the second elements in the list
print(name)                     #['Madonna', 'Cory', 'Nelly', 'Cory']

name.clear()                    #clear list
print(name)                     #[]

del name                        #Delete list
print(name)                     #NameError: name 'name' is not defined

note:pop()” delete the last bit of the list by default when the method is not indexed, and after entering the subscript (index position), delete the specified location element.

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -> None -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def clear(self): # real signature unknown; restored from __doc__
        """ L.clear() -> None -- remove all items from L """
        pass

remove() pop() clear() Partial source code

“Check “:It can be divided into two cases. One is to know a single index or one index to the corresponding element in another index. This time is obtained directly in a list name plus square brackets, which we can call a slice of the list, that is, to get the elements of the corresponding index in the list.The other is to know some of the elements in the list and want to query the location of the element where the element is located, and in this case we need to use the built-in.index() to achieve it. The example of the demonstration is as follows:

name = ["Madonna", "Cory", "Annie", "Nelly"]        #Create a list of class lists name

print(name[0])          #Madonna      Take the first element of the list
print(name[3])          #Nelly       Fourth elements of the list
print(name[-1]) #Nelly       The last element of the list
print(name[0:2])           #['Madonna', 'Cory']        Take the first to second elements of the list
print(name[:2])          #['Madonna', 'Cory']        Take the first to second elements of the list
print(name[0:-1])        #['Madonna', 'Cory', 'Annie']          Take the first to three elements of the list
print(name[1:])      #['Cory', 'Annie', 'Nelly'] Take a list of second to the last element
print(name[-3:-1]) #['Cory', 'Annie'] Take a list of second to third elements

print(name[:]) #['Madonna', 'Cory', 'Annie', 'Nelly'] Take the first to the last element of the list

print(name.index("Cory")) #1 Query the location of the index where the Cory element is located
print(name.index("Nelly")) #3 Query the location of the index where the Nelly element is located

note:

  • 1, square brackets slicing principle is” ignore the end of the head “, when looking for a single index of the corresponding element in the direct square brackets in the position can be added, when looking for an index to the other index corresponding to the correspondingWhen the element is in, the index position is placed in the square brackets, and the colon is used in the middle.:2, when the index position of input is 0 or -1 -1Time contains -1 The last element that corresponds to the last element does not include the last element.
  • 3″ and slice are taken from left to right, if yes.name[-1:-3]name[-3:-1].

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

index() Partial source code

“”Change”It is the simplest and most direct way to modify the elements corresponding to the index position directly by assigning values. The example of the demonstration is as follows:

name = ["Madonna", "Cory", "Annie", "Nelly"]        #Create a list of class lists name

name[0] = "Ayris"           #Assign the "Ayris" element to the 0 index position in the name list, that is, change the 0 index location element to "Ayris".
print(name)                 #['Ayris', 'Cory', 'Annie', 'Nelly']
print(name[0])              #Ayris

Others:count()  : statistics the number of times an element appears.reverse()  :back the element of the list;sort()  : to press list elementsASCII code ordering;

name = ["Madonna", "Cory", "Annie", "Nelly", "Cory"]        #Create a list of class lists name

print(name.count("Cory"))           #2    Count the number of "Cory" elements in the list

name.reverse()                      #Reverse list
print(name)                         #['Cory', 'Nelly', 'Annie', 'Cory', 'Madonna']

name.sort()                         #Sort by ASCII code
print(name)                         #['Annie', 'Cory', 'Cory', 'Madonna', 'Nelly']

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

   def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass

count() reverse() sort() Partial source code

 copyandcopy” in the song body:copy () copy” we call it deepcopy, that is, all copies of the original list, copy the list and new list into two completely independent list, do not interfere with each other.

import copy         #Importing the copy module

name = ["Madonna", "Cory", ["Annie", "Nelly"], "Cory"]        #Create a list of class lists name

b = name.copy()                 #Shallow copy, copy into a new list B
c = copy.deepcopy(name)         #Deep copy, copy into a new list C
print(b)                        #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']
print(c)                        #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']

del name[1]                     #Delete second elements in the original list
print(name)                     #['Madonna', ['Annie', 'Nelly'], 'Cory']
print(b)                        #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']
print(c)                        #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']

del name[1][1]                  #After deleting second elements, the first element of the first two elements (list elements) is deleted from the new list.
print(name)                     #['Madonna', ['Annie'], 'Cory']
print(b)                        #['Madonna', 'Cory', ['Annie'], 'Cory']
print(c)                        #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']

     def copy(self): # real signature unknown; restored from __doc__
        """ L.copy() -> list -- a shallow copy of L """
        return []

def deepcopy(x, memo=None, _nil=[]):
    """Deep copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.
    """

    if memo is None:
        memo = {}

    d = id(x)
    y = memo.get(d, _nil)
    if y is not _nil:
        return y

    cls = type(x)

    copier = _deepcopy_dispatch.get(cls)
    if copier:
        y = copier(x, memo)
    else:
        try:
            issc = issubclass(cls, type)
        except TypeError: # cls is not a class (old Boost; see SF #502085)
            issc = 0
        if issc:
            y = _deepcopy_atomic(x, memo)
        else:
            copier = getattr(x, "__deepcopy__", None)
            if copier:
                y = copier(memo)
            else:
                reductor = dispatch_table.get(cls)
                if reductor:
                    rv = reductor(x)
                else:
                    reductor = getattr(x, "__reduce_ex__", None)
                    if reductor:
                        rv = reductor(4)
                    else:
                        reductor = getattr(x, "__reduce__", None)
                        if reductor:
                            rv = reductor()
                        else:
                            raise Error(
                                "un(deep)copyable object of type %s" % cls)
                if isinstance(rv, str):
                    y = x
                else:
                    y = _reconstruct(x, memo, *rv)

    # If is its own copy, don't memoize.
    if y is not x:
        memo[d] = y
        _keep_alive(x, memo) # Make sure x lives at least as long as d
    return y

copy() copy.deepcopy() Partial source code

The loop of the list:We can use two methods to implement the list. The first one uses a circular statement to implement the printing effect of each element. The result of printing is not a list but a single element; the second is a simple imitation. for 

name = ["Madonna", "Cory", ["Annie", "Nelly"], "Cory"]        #Create a list of class lists name

for i in name:          #for Elements of a loop print list
    print(i)            #Madonna    Cory    ['Annie', 'Nelly']  Cory

print(name[::])         #['Madonna', 'Cory', ['Annie', 'Nelly'], 'Cory']
print(name[0:3:1])      #['Madonna', 'Cory', ['Annie', 'Nelly']]
print(name[::2])        #['Madonna', ['Annie', 'Nelly']]