简体   繁体   English

如何使用 Python 3 获取 2D 或任何 nD 数组中的不同值?

[英]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 .无需导入任何其他包,如collectionsitertools

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.

相关问题 我如何从二维数组中获取价值? -Python - How can I get value from 2d array? - Python 我可以使用列表理解在 python 的二维数组中获取输入吗?? 以及如何为 nD 数组实现它? - Can I Use the List Comprehensions for taking input in the 2D Array in the python ??. And how it can be implemented for the nD array? 如何从2D python数组获取列? - How can I get a column from a 2D python array? 如何使用for循环在python中编写2D数组 - How can I write a 2D array in python using for loop 如何在python numpy的二维数组中将位置(第2、第3或第4等)转换为索引(第1位置为00,第2位置为01等)? - how can I convert position (2nd, 3rd or 4th etc ) to index(00 for 1st position, 01 for 2nd etc) in 2D array in python numpy? 如何在 python 中的二维列表中搜索值 - How do I search for a value inside a 2d list in python 如何在Python中将图像数组转换为2D数组 - How can I convert an array of images to a 2D array in Python Python 2D数组-通过键获取值 - Python 2D Array - Get Value by Key 在Python中,如何获取2D数组中“列”的最大值? - In Python how do I get the max value of a 'column' in a 2D array? 如何从二维数组中选择值并添加到另一个二维数组 python - How can i select values from 2d array and add to another 2d array python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM