For a given list of lists, the task is to find the frequency of the character in each position of the sublist in the list of lists.
Input: lst = [[’X’,’ Y ’,’ X’], [’Z’,’ Y’, ’X’], [’ Y’, ’Y’,’ Y’], [’Z’,’ Z’, ’X’], [ ’Y’,’ Z’, ’X’]], character =’ X’ Output: [0.2, 0.0, 0.8]
Explanation:
We have 3 items in each sublist, we need to find the position & # 39; X & # 39; at positions 0, 1 and 2. For position 0 in all sublists we have:
"x" in the first sublist at position zero,
& # 39; z & # 39; in the second sublist at position zero,
& # 39; y & # 39; in the third sublist at the zero position,
& # 39; z & # 39; in the fourth sublist at the zero position and
& # 39; y & # 39; in the fifth sublist at position zero.
So, we have 1 occurrence of & # 39; x & # 39; at position 1 in the whole sublist, therefore Occurrence = 1/5 = .2
For position 1 in the sublist there is no occurrence & # 39; x & # 39;, therefore Occurrence = 0/5 = 0.
For Position 2 we have 4 occurrences & # 39; x & # 39; in a sublist, so Occurrence = 4/5 = 0.8
Let’s discuss some of the ways this can be done.
Method # 1: Using Iteration
|
Exit:
Initial list of list is: [[’X’, ’Y’, ’X’], [’Z’, ’Y’, ’X’], [’Y’, ’Y’, ’Y’], [’Z’, ’Z’, ’X’] , [’Y’, ’Z’, ’X’]]
Occurrence of ’X’ in list is [0.2, 0.0, 0.8]
Method # 2: Using Zip
|
Output:
Initial list of list is: [[’X’, ’Y’, ’X’], [’Z’, ’Y’, ’X’], [’Y ’,’ Y ’,’ Y ’], [’ Z ’,’ Z ’,’ X ’], [’ Y ’,’ Z ’,’ X ’]]
Occurrence of’ X ’in list is [0.2, 0.0, 0.8]
Method # 3: Using Pandas
|
Output:
Initial list of list is: [[’X’, ’Y’, ’X’], [’Z’, ’Y’, ’X’], [’Y’, ’Y ’,’ Y ’], [’ Z ’,’ Z ’,’ X ’], [’ Y ’,’ Z ’,’ X ’]]
Occurrence of’ X ’in list is
0 0.2
1 0.0
2 0.8
dtype: float64