[Tutor] Help on best way to check resence of item inside list
Peter Otten
__peter__ at web.de
Tue May 27 11:13:23 CEST 2014
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.
You mean you have people who are members in more than one club? You can
still use a dictionary if you make the value a list:
# untested code!
membership = {}
club = "club_of_people_who_are_not_in_any_club"
members = ["Erwin", "Kurt", "Groucho"]
for name in members:
# can be simplified with dict.setdefault() or collections.defaultdict
if name in membership:
membership[name].append(club)
else:
membership[name] = [club]
Put that in a loop over (club, members) pairs, and you'll end up with a dict
that maps name --> list_of_clubs.
Then iterate over the lines in the file:
with open("file.in") as source:
for line in source:
name = line.strip()
if name in membership:
print(name, *membership[name])
else:
print(name, "no")
>
> In the end I wan to have
>
>
> mary clubA clubB
> luke clubA
> luigi no
> Thanks in advance for any help
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list