如何在二维矩阵中逐行查找每个元素的频率?
How to find frequency of every element row wise in a 2D matrix?
我有一个 2D 列表作为 temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
我想获得连续元素的最大频率。例如,为此列表取索引 1。我们将“-1.0”的频率设置为 3,并且在该列表中是最大值。
我正在做这样的事情。但是得到 0 作为输出。有人可以帮忙吗
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
ct=0
maxi=0
for i in range(len(temp)):
for j in range(len(temp[i])):
ct=temp.count(temp[i][j])
maxi=max(ct,maxi)
在遍历列表列表 temp
时,您可以使用 python built-in 库 Counter
和方法 most_common()
。如下:
# sample data
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
from collections import Counter
for lst in temp:
# return the top most common value and its frequency
r = dict(Counter(lst).most_common(1))
print(r)
输出:
{0.5: 2}
{-1.0: 3}
{0.5: 2}
{-1.0: 3}
{-1.0: 3}
{-1.0: 3}
您的代码有误。
我在下面修复了它。
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
ct=0
maxi=0
for i in range(len(temp)):
for j in range(len(temp[i])):
ct=temp[i].count(temp[i][j])
maxi=max(ct,maxi)
print(maxi)
我有一个 2D 列表作为 temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]] 我想获得连续元素的最大频率。例如,为此列表取索引 1。我们将“-1.0”的频率设置为 3,并且在该列表中是最大值。 我正在做这样的事情。但是得到 0 作为输出。有人可以帮忙吗
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
ct=0
maxi=0
for i in range(len(temp)):
for j in range(len(temp[i])):
ct=temp.count(temp[i][j])
maxi=max(ct,maxi)
在遍历列表列表 temp
时,您可以使用 python built-in 库 Counter
和方法 most_common()
。如下:
# sample data
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
from collections import Counter
for lst in temp:
# return the top most common value and its frequency
r = dict(Counter(lst).most_common(1))
print(r)
输出:
{0.5: 2}
{-1.0: 3}
{0.5: 2}
{-1.0: 3}
{-1.0: 3}
{-1.0: 3}
您的代码有误。
我在下面修复了它。
temp=[[0.5, 0.5, 2.0], [0.5, 0.5, -1.0, -1.0, -1.0], [0.5, 0.5, 2.0, -0.25], [-1.0, 2.0, -1.0, -1.0], [2.0, -1.0, -1.0, -1.0], [-1.0, -0.25, -1.0, -1.0]]
ct=0
maxi=0
for i in range(len(temp)):
for j in range(len(temp[i])):
ct=temp[i].count(temp[i][j])
maxi=max(ct,maxi)
print(maxi)