The list of

The problem

There is a list l1, L1 = [11, 22, 33, 44, 55], please delete the elements corresponding to the odd index (can not be deleted one by one, this L1 is just an example, the elements in it are variable).

The solution

First, eliminate a common writing method: delete one by one. Why exclude? Because when you delete an element, the following element changes position. For example, if the second item is deleted, the list becomes [11,33,44,55], and the next deletion becomes 55. So it’s not right.

There are three solutions.

Direct deletion method

Python uses list slicing to delete a list[start position: end position: length] where position refers to the index.

def del1(a):
    del list1[1: :2]
    print(list1)
Copy the code

Flashback deletion method

Delete backwards Deletes elements from back to front

2 = 0 4%

3%2=1 delete the element below 3

2 = 0 2%

1%2=1 Delete the element below 1

0%2=0 deletes from back to front. After 3 (subscript) is deleted, the element position before 3 (subscript) is not affected.

def del2(a):
    for i in range(len(list2)- 1.- 1.- 1) :if i % 2= =1:
            list2.pop(i)
    print(list2)
Copy the code

Think about it another way

A temporary list is generated to store the subscript elements that meet the criteria

def del3(a):
    temp = []
    for i in range(0,len(list3),2):
        temp.append(list3[i])
    print(temp)
Copy the code

The dictionary

The problem

Dic = {‘ k1 ‘:’ white ‘, ‘k2:’ Barry ‘to’ k3 ‘:’ nothing ‘, ‘age: 18} please bring all keys in the dictionary of k element keys to delete. So when you get this problem, someone says I’m going to delete them one by one, which is no good, because this dictionary is just an example, the elements in it are uncertain, so what do you do? You’re going to go through all the keys, delete the ones that match, right? Yeah, I got it. Oh, no, I got it. Please start your act.

The solution

Creates an empty list for storing keywords.

  1. Iterate over the keys in the dictionary and add them to the list if they match the criteria
  2. Iterate through the list, removing the dictionary values of the list one by one
dic = {'k1':'the white'.'k2':'barry'.'k3': 'nothing'.'age': 18}
def del1(a):
    l1 = []
    for key in dic:
        if 'k' in key:
            l1.append(key)
    for i in l1:
        dic.pop(i)
    print(dic)
Copy the code

Keys () is a built-in method of the DIC class. Keys () returns an object of type dict_keys that needs to be cast to list. Normal operation.

for i in list(dic.keys()):
    if 'k' in i:
        dic.pop(i)
print(dic)
Copy the code