def a():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h', 'z']
count = Counter(List_A)
List_C = [count.get(x) for x in List_B]
100000 loops, best of 5: 2.96 usec per loop
Using Counter() and checking for None:
def b():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h', 'z']
count = Counter(List_A)
List_C = []
for x in List_B:
val = count.get(x)
if val != None:
List_C.append(val)
100000 loops, best of 5: 3.45 usec per loop
Without checking None values:
def c():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h', 'z']
count = Counter(List_A)
List_C = []
for x in List_B:
List_C.append(count.get(x))
100000 loops, best of 5: 3.04 usec per loop
Using @Mafa's solution, which doesn't work if List_B have values that don't appear in List_A:
def d():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h']
occ = dict()
for x in List_A:
occ.setdefault(x, 0)
occ[x] += 1
List_C = [occ[x] for x in List_B]
100000 loops, best of 5: 2.59 usec per
Mafa's Solution with checks for existing values:
def e():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h']
occ = dict()
for x in List_A:
occ.setdefault(x, 0)
occ[x] += 1
List_C = [occ.get(x, 0) for x in List_B]
100000 loops, best of 5: 3.1 usec per loop
The two next functions were proposed by @Alex Waygood
def f():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h']
c = Counter(filter(set(List_B).__contains__, List_A))
List_C = [v for k, v in sorted(c.items())]
50000 loops, best of 5: 4.45 usec per loop
def g():
List_A = ['a', 'd','f','h','g','e','f','a','f','h','h','d','b','c','c','a']
List_B = ['a', 'b','c','d','e','f','g','h', 'z']
c = Counter(filter(List_B.__contains__, List_A))
List_C = [v for k, v in sorted(c.items())]
50000 loops, best of 5: 4.78 usec per loop
(Not sure if need to divide by two here -- apparently not --, since there are 50000 loops instead of 100000, if that is the case we have a clear winner here)