Python|在列表列表中的每个位置查找给定字符的频率
给定一个列表列表,任务是找到一个字符在列表列表中子列表每个位置的频率。
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]
解释:
我们在每个子列表中有 3 个元素,我们必须在位置 0、1 和 2 处找到“X”的位置。对于所有子列表中的位置0 ,我们有 -
'x' 在第一个子列表中的零位置,
'z' 在第二个子列表中的零位置,
'y' 在第三个子列表中的零位置,
'z' 在第四个子列表中的零位置和
'y' 在第五个子列表中的零位置。
因此,我们在所有子列表的位置 1 处出现 1 次“x”,因此,出现 = 1/5 = .2
对于位置1 ,我们在子列表中没有出现任何“x”,因此,出现 = 0/5 = 0。
对于位置2 ,我们在子列表中有 4 次出现“x”,因此,出现次数 = 4/5 = 0.8
让我们讨论可以执行此操作的某些方式。
方法#1:使用迭代
# Python code to find frequency of a character
# at every position of list in list of lists.
# Input list initialization
Input = [['X', 'Y', 'X'], ['Z', 'Y', 'X'],
['Y', 'Y', 'Y'], ['Z', 'Z', 'X'],
['Y', 'Z', 'X']]
Output = []
# Character Initialization
character = 'X'
# Output list initialization
for elem in range(len(Input[0])):
Output.append(0)
# Using iteration
for elem in Input:
for x, y in enumerate(elem):
if y == character:
Output[x]+= 1
for x, y in enumerate(Output):
Output[x] = y / len(Input)
# Printing
print("Initial list of list is :", Input)
print("Occurrence of 'X' in list is", 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]
方法 #2:使用 zip
# Python code to find frequency of a character
# at every position of list in list of lists.
# Input list initialization
Input = [['X', 'Y', 'X'], ['Z', 'Y', 'X'],
['Y', 'Y', 'Y'], ['Z', 'Z', 'X'],
['Y', 'Z', 'X']]
Output = []
# Character initialization
character = 'X'
# Using zip
Output = [elem.count(character)/len(elem)
for elem in zip(*Input)]
# Printing
print("Initial list of list is :", Input)
print("Occurrence of 'X' in list is", 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]
方法 #3:使用 Pandas
# Python code to find frequency of a character
# at every position of list in list of lists.
import pandas as pd
# Input list initialization
Input = [['X', 'Y', 'X'],
['Z', 'Y', 'X'],
['Y', 'Y', 'Y'],
['Z', 'Z', 'X'],
['Y', 'Z', 'X']]
# Defining character
character = 'X'
# using pandas
Output = pd.DataFrame(Input)
Output = Output.where(Output == character, 0).where(Output != character, 1)
# Printing
print("Initial list of list is :", Input)
print("Occurrence of 'X' in list is\n", Output.mean())
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