Comparing VBScript Arrays


(Dale Fugier) #1

Enjoy!

– Dale


#2

Hi Dale
the below code in Python is equivalent to VBscript?

# quanti elementi hanno lo stesso nome in due liste
a=(1,2,4,5,6,2,3,4,5,6,7,8)
b=(4,5,13,8,2)#,3,2,2,3,12)
diz={}
intsame=0
for i in b:  #trasformo b in dizionario
   diz[i]=0
print diz
for u in a: # controllo quanti elementi di a hanno la stessa chiave del dizionario
    if diz.has_key(u):intsame+=1
print intsame

Ciao Vittorio


#3

Hi Vittorio,

It’s way easier in Python…

a=(1,2,4,5,6,2,3,4,5,6,7,8)  
b=(4,5,13,8,2)
common=[]
for i in b:
    if i in a:
        common.append(i)
print common

[4, 5, 8, 2]

or even more compact…

a=(1,2,4,5,6,2,3,4,5,6,7,8)  
b=(4,5,13,8,2)
common=[i for i in b if i in a]
print common

Ciao, --Mitch


#4

And, if you want only unique values in the result:

a=(1,2,4,5,6,2,3,4,5,6,7,8)  
b=(4,5,13,8,2,3,2,2,3,12)  
common=[]
for i in b:
    if i in a and not i in common:
        common.append(i)
print common

[4, 5, 8, 2, 3]

Cool, no?
Ciao, --Mitch


#5

Hi Mitch
You are fantastic.
Ciao Vittorio


#6

No, not me, Python!

–Mitch


(Steve Baer) #7

Come on Mitch, I’m waiting for a sample with sets in python :wink2:
http://docs.python.org/2/library/sets.html


#8

What, you mean

a=set([1,2,4,5,6,2,3,4,5,6,7,8])    
b=set([4,5,13,8,2,3,2,2,3,12]) 
c=list(b.intersection(a))
print c

[2, 3, 4, 5, 8]

Yeah, OK, I always forget about sets… :confounded:
–Mitch


(Steve Baer) #9

Four lines - pretty good. I could get it down to two lines, but less readable than your version

a=set([1,2,4,5,6,2,3,4,5,6,7,8]).intersection([4,5,13,8,2,3,2,2,3,12])
print list(a)

#10

Oh, you could have gotten it down to one, but who’s counting… :wink:

print list(set([1,2,4,5,6,2,3,4,5,6,7,8]).intersection([4,5,13,8,2,3,2,2,3,12]))