[英]How can I get the distinct value inside 2D or any nD array using Python 3?
I'm trying to get the distinct value(s) inside a 2D or nD array and then print some message when it saw one or more.我试图在 2D 或 nD 数组中获取不同的值,然后在看到一个或多个时打印一些消息。
arr = [[1,1,3],[2,4,2]]
Distinct values inside array: 3, 4
Duplicated values inside array: 1, 2
1 appeared 2 times
2 appeared 2 times
I tried this initial code but no luck (incomplete code):我试过这个初始代码但没有运气(不完整的代码):
import numpy as np
R = int(input("Enter the number of rows: "))
C = int(input("Enter the number of columns: "))
matrix = []
print("Enter the numbers:")
for i in range(R):
a =[]
for j in range(C):
a.append(int(input()))
matrix.append(a)
arr = np.array(matrix).flatten()
def areDistinct(arr) :
n = len(arr)
s = set()
for i in range(0, n):
s.add(arr[i])
return (len(s) == len(arr))
if (areDistinct(arr)):
print("DISTINCT")
else :
print("DUPLICATED")
As you tagged your question with Numpy tag, I suppose that you are looking for a Numpythonic solution (in contrast to plain Pytnon).当您使用Numpy标记标记问题时,我想您正在寻找NumPythonic解决方案(与普通 Pytnon 相比)。
So start with the necessary import:因此,从必要的导入开始:
import numpy as np
I assume that you created your arr something like:我假设您创建的arr类似于:
arr = np.array([[1,1,3],[2,4,2]])
First compute unique values and their respective counts (how many times each value occurs):首先计算唯一值及其各自的计数(每个值出现多少次):
vals, cnts = np.unique(arr.flatten(), return_counts=True)
The second step is to compute uniqueness indicators:第二步是计算唯一性指标:
uniq = cnts == 1
For your data sample the results are:对于您的数据样本,结果是:
array([1, 2, 3, 4])
array([2, 2, 1, 1], dtype=int64)
array([False, False, True, True])
Then, to generate your expected printout, run:然后,要生成预期的打印输出,请运行:
print(f'Distinct values inside array: {", ".join(map(str, vals[uniq]))}')
print(f'Duplicated values inside array: {", ".join(map(str, vals[~uniq]))}')
for i in [ind for ind, x in enumerate(uniq) if ~x]:
print(f'{vals[i]} appeared {cnts[i]} times')
No need to import any other packages like collections or itertools .无需导入任何其他包,如collections或itertools 。
arr = [[1,1,3],[2,4,2]]
res = dict()
# compute histogram
for inner_arr in arr:
for a in inner_arr:
if a in res:
res[a] += 1
else:
res[a] = 1
# scan histogram and check for distinct values
for r in res:
if res[r] == 1:
print(f"The value {r} appeared once.")
else:
print(f"The value {r} appeared {res[r]} times.")
you can easily scan res and return all keys that has associated values 1. You can see res dictionary has a histogram.您可以轻松地扫描 res 并返回具有关联值 1 的所有键。您可以看到 res 字典有一个直方图。
You can try flattening the array and then putting it through the built-in Counter
您可以尝试展平阵列,然后将其放入内置
Counter
flattened = flatten(arr) counts_of_values = Counter(flattened)展平 = 展平(arr) counts_of_values = 计数器(展平)
and then just filter based on the counts, so like this:然后根据计数进行过滤,像这样:
from itertools import chain
from collections import Counter
flattened = list(chain(*arr))
c = Counter(flattened)
distinct = [k for k, v in c.items() if v < 2]
duplicated = [k for k, v in c.items() if v >= 2]
values=dict()
arr=[[1,1,3,4,6,6,7,4,3,2,5,7],[3,2,1]]
for i in arr:
for j in i:
if j in values:
values[j]+=1
else:
values[j]=1
distinct = []
duplicate = dict()
for i in values:
if values[i] == 1:
distinct.append(i)
else:
duplicate[i] = values[i]
print(distinct)
print(duplicate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.