A "for" with "list" question.
Emile van Sebille
emile at fenx.com
Sat Aug 31 17:56:38 EDT 2002
Mauro:
> I've got 2 lists and I want to print print only the common, itens in
> both lists and the not common after.
>
> Exemple:
>
> a = [0,1,2]
> b = [1,2,3]
>
> 1° Print only -> 1 and 2
> Because the 1 and 2 are the only than appears in both lists.
>
> 2° Print only -> 0 and 3
> This are the itens than are only in their lists.
>
In current cvs you can do:
import sets
a = sets.Set([0,1,2])
b = sets.Set([1,2,3])
print 'a & b ', a & b
print 'a | b ', a | b
print '(a | b) - (a & b) ',(a | b) - (a & b)
And in older versions you could do:
a = [0,1,2]
b = [1,2,3]
mix = {}
for source in (a,b):
for item in source:
count = mix.setdefault(item, 0)
mix[item] = count + 1
print 'a & b ', mix.keys()
print 'a | b ', [ ii for ii,jj in mix.items() if jj == 2 ]
print '(a | b) - (a & b) ', [ ii for ii,jj in mix.items() if jj == 1 ]
HTH,
Emile van Sebille
emile at fenx.com
More information about the Python-list
mailing list