[Tutor] Help on best way to check resence of item inside list
Steven D'Aprano
steve at pearwood.info
Tue May 27 14:05:45 CEST 2014
On Tue, May 27, 2014 at 10:05:30AM +0200, jarod_v6 at libero.it wrote:
[...]
> with open("file.in") as p:
> mit = []
You have lost the indentation, which makes this code incorrect.
But the rest of the code is too complicated.
> 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)
Look at the result you want to get:
> mary clubA clubB
> luke clubA
> luigi no
That suggests to me that the best data structure is a dict with sets:
{'mary': set(['clubA', 'clubB']),
'luke': set(['clubA']),
'luigi': set(),
}
Something like this should work:
names = {}
with open("file.in") as p:
# This assumes the data file is one name per line.
for line in p:
name = line.strip()
s = names.get(name, set()) # If name not in the names,
# return an empty set.
if name in clubA:
s.add("clubA")
if name in clubB:
s.add("clubB")
names[name] = s
print(names)
And I think that should work.
--
Steven
More information about the Tutor
mailing list