[Tutor] Help on best way to check resence of item inside list

Mark Lawrence breamoreboy at yahoo.co.uk
Tue May 27 10:48:27 CEST 2014


On 27/05/2014 09:05, jarod_v6 at libero.it wrote:
> Dear All
>
> clubA= ["mary","luke","amyr","marco","franco","lucia", "sally","genevra","
> electra"]
> clubB= ["mary","rebecca","jane","jessica","judit","sharon","lucia", "sally","
> Castiel","Sam"]
>
> I have a list of names that I would to annotate  in function of presence in
> different clubs:
>
> my input files is a long file where I have this :
>
> mary
> luke
> luigi
> jane
> jessica
> rebecca
> luis
> ################################################à
>
> with open("file.in") as p:
> mit = []
> for i in p:
>     lines =i.strip("\n").split("\t")
>     if  (lines[0] in clubA:
>                G =lines[-1] +["clubA"]
>     else:
>             G = lines[-1] +["no"]
> mit.append(G)
>
>
> for i in mit:
>     if i.strip("\n").split("\t")[0] in clubB:
>           G =lines[-1] +["clubB"]
>     else:
>             G = lines[-1] +["no"]
>    finale.append(G)
> ###############################################################
> I just wonder if is appropriate to use a loops to check if is present the
> value on a list. Is it the right way? I can use a dictionary because I have
> many repeated names.
>
> In the end I wan to have
>
>
> mary  clubA clubB
> luke clubA
> luigi  no
> Thanks in advance for any help

You can use the in keyword to check for an item in a list.  However a 
very quick glance at your code suggests that you could cut out the list 
completely and do the same using the in keyword against your dict. 
Better still I think the defaultdict is what you need here, I'll leave 
you to look it up as I must dash :)


-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com




More information about the Tutor mailing list