Reputation: 759
There are several similar questions around that suggest using any()
with sets, however mine is a bit different in a way that I want to get the most effective and Pythonic way of forming a new array out of existing arrays based on membership.
I have the following array [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 6], [2, 4, 5, 6, 9, 1, 4, 5, 6, 4, 5, 6], [1, 2, 9, 4, 5, 6, 7, 7, 8, 5]]
What I need is a way to form a new object {[4, 5, 6] : 6}
where [4, 5, 6]
is the key, and 6
is the number of times the key sequence appears in the array above.
I have achieved the result by making a function with simple for loops, but I don't think it is the most Pythonic and efficient way of achieving it. I was thinking of using map()
and filter()
as well.
What would be the most efficient and Pythonic way of achieving the result?
Upvotes: 0
Views: 59
Reputation: 42143
You could use Counter from collection and initialize a Counter object with all the 3 number tuples in the various lists. You will then be able to get the count of any 3 number series instantly:
lists = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 6], [2, 4, 5, 6, 9, 1, 4, 5, 6, 4, 5, 6], [1, 2, 9, 4, 5, 6, 7, 7, 8, 5]]
from collections import Counter
counts = Counter( (a,b,c) for lst in lists for a,b,c in zip(lst,lst[1:],lst[2:]) )
print(counts[(4,5,6)]) # 6
counts
is a Counter dictionary that will contain:
{ (4, 5, 6): 6, (5, 6, 7): 2, (1, 2, 3): 1,
(2, 3, 4): 1, (3, 4, 5): 1, (6, 7, 8): 1,
(7, 8, 9): 1, (8, 9, 10): 1, (9, 10, 4): 1,
(10, 4, 5): 1, (2, 4, 5): 1, (5, 6, 9): 1,
(6, 9, 1): 1, (9, 1, 4): 1, (1, 4, 5): 1,
(5, 6, 4): 1, (6, 4, 5): 1, (1, 2, 9): 1,
(2, 9, 4): 1, (9, 4, 5): 1, (6, 7, 7): 1,
(7, 7, 8): 1, (7, 8, 5): 1 }
If you only need that single series' count you can use the list comprehension directly:
len([s for lst in lists for s in zip(lst,lst[1:],lst[2:]) if s==(4,5,6)])
Upvotes: 1
Reputation: 11
best way to maintain a mapping of elements in an array to a value is a hash table. as @JacobIRR mentioned {[4, 5, 6] : 6} is not valid because you cant have multiple keys associated to a value. i cant give you an exact solution to your problem as you didnt mention how your function works. if your algorithm dosent depend on a list as a key,you can try {6 :[4, 5, 6]} will be a valid solution as HashMap doesn't allow duplicate keys but allows duplicate values.
Upvotes: 1