[Tutor] Help on best way to check resence of item inside list
Dave Angel
davea at davea.name
Tue May 27 12:17:03 CEST 2014
"jarod_v6 at libero.it" <jarod_v6 at libero.it> Wrote in message:
> 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
There are numerous errors in the above code. You should use
copy/paste, so we don't waste energy identifying errors that
don't even exist in your actual code. As it stands, it wouldn't
even compile.
But even if you fix the typos and indentation errors and
initialization errors, you still have logic errors if you want
the output you specify. First, the second loop doesn’t set the
lines variable at all, but just uses the value from the last
iteration of the first loop. Second, even if you untangle that,
luigi would end up with two 'no's, not one.
You don't say what list could have repeats. I don't see any in
your sample data. You also don't say how they should be treated.
For example, Are all seventeen mary's in clubA?
Now to your specific question. You aren't using the loops to
check the lists for a name. You're quite reasonably using
'in'.
You can accomplish your apparent goal much more reasonably by
using a single loop and more complex if elif and
else.
--
DaveA
More information about the Tutor
mailing list