While looking at someone else's notebook on Kaggle, I found the following statement:
import random
import string
import collections
action_seq = [2,1]
action_seq, table = [], collections.defaultdict(lambda: [0, 0, 0])
key = ''.join([str(a) for a in action_seq[:-1]])
table[key][0] += 1
print(table[key][0])
The above execution result is as follows.
1
To be honest, I had no idea what would result in a "1". I also checked the processing contents of collections.defaultdict () and lambda, but I still don't understand. In the first place, I couldn't imagine what the result would be if I did "+ = 1" on the array.
I was able to understand how to move by performing the following debugging.
import random
import string
import collections
action_seq, table = [], collections.defaultdict(lambda: [0, 0, 0])
action_seq = [2,1]
key = ''.join([str(a) for a in action_seq[:-1]])
print(table)
table[key][0] += 1
print(table)
table[key][1] += 1
print(table)
table[key][2] += 1
print(table)
The result is as follows.
defaultdict(<function <lambda> at 0x7fd38dfa43b0>, {})
defaultdict(<function <lambda> at 0x7fd38dfa43b0>, {'2': [1, 0, 0]})
defaultdict(<function <lambda> at 0x7fd38dfa43b0>, {'2': [1, 1, 0]})
defaultdict(<function <lambda> at 0x7fd38dfa43b0>, {'2': [1, 1, 1]})
What can be seen from this result is that "table [key] [0] + = 1" is processed with the following configuration.
table[key]...Set table key to "2"
[0]...Set by default[0,0,0]Specify the first column of
+= 1...Add 1 to the value in the first column of the table key 2 array
It turned out that [0] specified after [key] is a column specification.
It took me a long time to understand this process, so I hope it helps.
Recommended Posts