0
votes

rechercher une chaîne dans une liste de listes

J'ai une liste avec des listes de chaînes:

cleanCloud = []

for i in cloud:
    if i[0][:3] == 'FEW':
        cleanCloud.append(i[0][8:])
    elif i[0][:3] == 'SCT':

et je voudrais supprimer toutes les instances de «FEW» pour renvoyer quelque chose comme:

cleanCloud = [['SCT015, SCT040'], ['SCT025'], ['SCT045'], [], [], []]


2 commentaires

Comment avez-vous obtenu 'SCT045' deux fois?


Pardon. Correction de la faute de frappe.


4 Réponses :


0
votes

Il semble que vous ayez besoin d'une expression régulière avec une compréhension de liste.

[['SCT015', 'SCT040'], ['SCT025'], ['SCT045'], [], [], []]

Sortie:

import re
cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'],['FEW020, FEW040'], ['FEW010 FEW020, FEW040'], ['FEW012, FEW020, FEW040']]

print( [re.findall(r"\bSCT\d{3}\b", j) for i in cloud for j in i] )


0 commentaires

0
votes

Vous pouvez essayer:

cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'], ['FEW020, FEW040'], ['FEW010, FEW020, FEW040'], ['FEW012, FEW020, FEW040']],

output_cloud = []
for single_element in cloud[0]:
    data = (single_element[0]).split(", ")
    output_data = []
    for sigle_data in data:
        if "FEW" not in sigle_data:
            output_data.append(sigle_data)

    output_string = ", ".join(output_data)
    print(output_string)

    output_cloud.append([output_string])

print(output_cloud)


0 commentaires

0
votes

Code plus simple sans utiliser re

cleanCloud = []
for inner_list in cloud:
    new_inner_list = []
    for item in inner_list:
        if 'FEW' not in item:
            new_inner_list.append(item)
    cleanCloud.append(new_inner_list)
 print(cleanCloud)


0 commentaires

0
votes

vous pouvez le faire comme:

[['SCT015, SCT040'], ['SCT025'], ['SCT045'], [], [], []]

sortie:

cloud = [['SCT015, SCT040'], ['FEW015, SCT025'], ['FEW015, SCT045'],['FEW020, FEW040'], ['FEW010, FEW020, FEW040'], ['FEW012, FEW020, FEW040']]

for i in range(len(cloud)):
    cloud[i] = [", ".join(filter(lambda x:  'FEW' not in x, cloud[i][0].split(', ')))]
    cloud[i] = cloud[i] if cloud[i] != [''] else []

print (cloud)


0 commentaires