I'm trying to convert values in nested list from dict
list1 = [["a","b"],["c"],["a","d"]]
list2 = [["a","b"],["c"],[""],["a","d"]]
dict_form = {"a":"app","b":"bold","c":"cafe","d":"dot"}
Expected output
new_list = [["app","bold"],["cafe"],["app","dot"]]
result_1 = [["app","bold"],["cafe"],[""],["app","dot"]]
What I have tried:
result = [[dict_form[i] for i in j] for j in new_list]
Use a 2-level list comprehension
result = [[dict_form[k] for k in sublist] for sublist in list1]
print(result) # [['app', 'bold'], ['cafe'], ['app', 'dot']]
Timeit
on 20 loops of 200k iterations
# List comprehension : [[dict_form[k] for k in sublist] for sublist in list1]
python -m timeit -r 20 -n 200000 -s "list1 = [['a','b'],['c'],['a','d']];dict_form = {'a':'app','b':'bold','c':'cafe','d':'dot'}" "[[dict_form[k] for k in sublist] for sublist in list1]"
200000 loops, best of 20: 1.74 usec per loop
# list/map : list(map(lambda x: list(map(dict_form.get, x)), list1))
python -m timeit -r 20 -n 200000 -s "list1 = [['a','b'],['c'],['a','d']];dict_form = {'a':'app','b':'bold','c':'cafe','d':'dot'}" "list(map(lambda x: list(map(dict_form.get, x)), list1))"
200000 loops, best of 20: 3.2 usec per loop
So more performant on normal list length, and same on huge list (see Derek post)
Here is how you can use a nested list comprehension:
list1 = [["a","b"],["c"],["a","d"]]
dict_form = {"a":"app","b":"bold","c":"cafe","d":"dot"}
new_list = [[dict_form[k] for k in ls] for ls in list1]
print(new_list)
Output:
[['app', 'bold'], ['cafe'], ['app', 'dot']]
another way would be to just use map:
list(map(lambda x: list(map(dict_form.get, x)), list1))
output:
[['app', 'bold'], ['cafe'], ['app', 'dot']]
slight variation:
[*map(lambda x: [*map(dict_form.get, x)], list1)]
As a follow up to @azro's timings, I generated a much larger input list1 with the same kind of structure..
using the current input from the OP, approx:
nested list comprehension = 0.000000833 s
map method = 0.000001440 s
map method variation = 0.000001180 s
with a MUCH larger but similar list, approx:
nested list comprehension = 0.054890156 s
map method = 0.050899744 s
map method variation = 0.065859318 s
So I guess the most efficient solution (from those provided) depends on the size of your actual list, seems the map method tends to perform the best as the lists get larger
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.