I have a list of strings like the following:
strings = ["acbd", "abc", "acbde", "abc"]
And a dictionary containing numeric representations of each character:
dict_ = {"a":[0.4, 0.3, 0.8, -0.1], "b":[1.5, -1.6, 1.2], "c":[7.4, 4.3], "d":[4.23, 0.5, 0.9, 0.5, 1.7], "e":[1.5, 8.1]}
How can I get a numeric representation for each string in strings? For example, for "acbd", I want a concatenated list of the constituent characters in order: [0.4, 0.3, 0.8, -0.1, 7.4, 4.3, 1.5, -1.6, 1.2, 4.23, 0.5, 0.9, 0.5, 1.7]. I want an output with a list of lists, with each list being a numeric representation of the string.
What is the most efficient way of doing this also?
My real data has over 100000 strings and all 26 characters.
Here's one solution using itertools.chain and a list comprehension.
This has no optimisation for repeated strings. I suggest you test with your data to see if performance is adequate.
from itertools import chain
res = [list(chain.from_iterable(map(dict_.get, i))) for i in strings]
print(res)
[[0.4, 0.3, 0.8, -0.1, 7.4, 4.3, 1.5, -1.6, 1.2, 4.23, 0.5, 0.9, 0.5, 1.7],
[0.4, 0.3, 0.8, -0.1, 1.5, -1.6, 1.2, 7.4, 4.3],
[0.4, 0.3, 0.8, -0.1, 7.4, 4.3, 1.5, -1.6, 1.2, 4.23, 0.5, 0.9, 0.5, 1.7, 1.5, 8.1],
[0.4, 0.3, 0.8, -0.1, 1.5, -1.6, 1.2, 7.4, 4.3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With