0

我有这个:

array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]

并想创建这个:

multiArray1 = {[1,2,3]:2, [2,1,3]:2}
multiArray2 = {[1,2,3]:4, [2,1,3]:1}

问题:我试图将 multiArray1 和 multiArray2 作为包含相同值的字典,但键分别给出了这些值在 array1 和 array2 中出现的次数。

我不确定要在我的代码中更改什么。任何帮助将不胜感激。谢谢。

from collections import defaultdict

array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]

def f(arrA,arrB):
    multiArray1 = {}
    multiArray2 = {}

    intersect = set(map(tuple,arrA)).intersection(map(tuple,arrB))
    print(set(map(tuple,arrA)).intersection(map(tuple,arrB)))

    for i in intersect:
        multiArray1.update({i:0})
        multiArray2.update({i:0})
    print(multiArray1)
    print(multiArray2)

    multipleArray1 = {}
    multipleArray2 = {}

    for i in intersect:
        for j in range(len(arrA)):
            if str(tuple(arrA[j])) in set(intersect):
                multiArray1[tuple(arrA[j])].append(j)
                print(multiArray1)

                multipleArray1 = defaultdict(list)
                for key, value in multipleArray1:
                    multipleArray1[i].append(j)
                    print(multipleArray1)

    for j in range(len(arrB)):
        if str(tuple(arrB[j])) in set(intersect):
            multiArray2[tuple(arrB[j])].append(j)

            multipleArray2 = defaultdict(list)
            for key, value in multipleArray2:
                multipleArray2[i].append(j)
                print(multipleArray2)

    print(multiArray1)
    print(multiArray2)

f(array1,array2)

从上面的代码中得到的输出是这样的:

{(2, 1, 3), (1, 2, 3)}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}
{(2, 1, 3): 0, (1, 2, 3): 0}
4

2 回答 2

1

正如有人指出的那样,您不能使用列表。在我的方法中,您需要将子列表转换为元组,然后更新字典。

In [48]: array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]

In [49]: array1 = list(map(lambda x: tuple(x), array1))

In [50]: array1
Out[50]: [(1, 2, 3), (1, 2, 3), (2, 1, 3), (2, 1, 3), (1, -2, 3)]

In [51]: res = dict()

In [52]: for i in array1:
    if i not in res:
        res[i] = 1
    else:
        res[i] += 1
   ....:         

In [53]: res
Out[53]: {(1, -2, 3): 1, (1, 2, 3): 2, (2, 1, 3): 2}
于 2016-06-05T14:05:30.990 回答
0

诀窍是,在将它们作为字典的键之前将它们转换为字符串,因为您不能将列表作为字典的键。

dct1 = {}
dct2 = {}
array1 = [[1,2,3],[1,2,3],[2,1,3],[2,1,3],[1,-2,3]]
array2 = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,2,3],[2,1,3]]

for x in array1:
    cnt = array1.count(x)
    dct1[str(x)] = cnt #here str(x) convert the list to string
for x in array2:
    cnt = array2.count(x)
    dct2[str(x)] = cnt #again here


print (dct1)
print (dct2)

输出

>>> 
{'[1, 2, 3]': 2, '[1, -2, 3]': 1, '[2, 1, 3]': 2}
{'[1, 2, 3]': 4, '[2, 1, 3]': 1, '[0, 2, 3]': 1}
>>> 
于 2016-06-05T13:59:19.740 回答