Python Remove item from list

I'm really new to Python, just working on it, since another guy on my team has left and need to work a bit on the line, so I apologize if this is a stupid question.

I need to remove elements from the list (they will contain a certain phrase), and googled and tried several ways, but it does not seem to work.

What I have

def get_and_count_card_files(date): # Retrieve the DC and SD card files dc_files = dc_card_files.get_dc_files(dc_start_location, date) sd_files = sd_card_files.get_sd_files(sd_start_location) print(dc_files) if '*NoCover*' in dc_files: dc_files.remove('*NoCover*') 

Dc_files is a list (group of file names), and I need to delete everything that has NoCover in the file name. It exists because the print function shows me what it does.

Does anyone know what I'm doing wrong

enter image description here

+5
source share
4 answers

With this code snippet * will not do the globe or regular expression in these contexts:

 if '*NoCover*' in dc_files: dc_files.remove('*NoCover*') 

therefore it would be better to say:

 if 'NoCover' in dc_files: 

However, we need to find the desired entry to delete in the list without using wildcards.

For a small list, you can iterate over it. Understanding the list would do:

 new_dc_files = [dc for dc in dc_files if 'NoCover' not in dc] 

This is a compact way of saying:

 new_dc_files = list() for dc in dc_files: if 'NoCover' in dc: continue new_dc_files.append(dc) 
+6
source

if '*NoCover*' in dc_files: will search for an item in the dc_files list that explicitly matches "NoCover".

What you can do is

 # Iterate over the list backwards, this will stop you from skipping elements # you want to check in the next iteration if you remove something for index, dc_file in enumerate(dc_files[::-1]): if 'NoCover' in dc_file: dc_files.pop(index) 

Alternatively, you can use regular expressions if you have more complex pattern matching requirements.

0
source

You can use Python list comprehension to filter out unwanted entries:

 def get_and_count_card_files(date): # Retrieve the DC and SD card files dc_files = dc_card_files.get_dc_files(dc_start_location, date) sd_files = sd_card_files.get_sd_files(sd_start_location) print(dc_files) dc_files = [file for file in dc_files if 'NoCover' not in file] 
0
source

You are looking for Python list comprehension :

 dc_files = [el for el in dc_files if 'NoCover' not in el] 

So what this basically does is filter all elements from dc_files that don't contain the string 'NoCover' .

Note that if 'NoCover' not in el is executed for each element of the list, and the in operator for the string simply checks what exactly you wanted to do, i.e. Is 'NoCover' substring of el .

0
source

Source: https://habr.com/ru/post/1231931/


All Articles