0
votes

Liste de filtrage par condition avec python

def myFunction(cond_list, input_list):
    res = []
    data = list(set(input_list))  # filter duplicate elements
    for i in cond_list:
        for j in data:
            if i in j:
                res.append(i)
    return res

cond = ['cat', 'rabbit']  
input_list = ['', 'cat 88.96%', '.', 'I have a dog', '', 'rabbit 12.44%', '', 'I like tiger']
result = myFunction(cond_list=cond, input_list=input_list)
print(result)  # the input list have: ['cat', 'rabbit']
I have a function. Is there any better way to modify my function according to the conditions?

4 commentaires

Que voulez-vous que votre fonction fasse? Pouvez-vous partager quelques échantillons d'entrées et de sorties?


Est la sortie attendue ['CAT 88.96%', 'Lapbit 12.44%'] ?


@Deveshkumarsingh non, obtenez la chaîne I réglage -> ['Cat', 'Lapbit']


Donc, si votre entrée et votre sortie sont identiques? Quelle est la fonction faire?


4 Réponses :


1
votes

Si je vous comprends correctement, c'est ce que vous recherchez?

cond = ['cat', 'rabbit']  # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger 85.44%']
[i for i in cond for j in input_list if i in j]


0 commentaires

0
votes
cond = ['cat', 'rabbit']  # filter duplicate elements
input_list = ['', 'cat 88.96%', '.', 'dog 40.12%', '', 'rabbit 12.44%', '', 'tiger 
85.44%']
matching = list(set([s for s in input_list if any(xs in s for xs in cond)]))

for i in matching: 
   print(i)

0 commentaires

0
votes

Ceci est une approche à l'aide de regex et une compréhension de liste

ex: xxx

sortie: < / p> xxx


0 commentaires

1
votes

Vous pouvez utiliser iTertools.Production pour générer le paires à comparaison: xxx


0 commentaires