我有这个:
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}
答案 0 :(得分: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}
答案 1 :(得分:0)
诀窍是,在将它们作为dict的键之前将它们转换为字符串,因为你不能将列表作为字典的键。
PopupWindow pw = new PopupWindow(layout, (int)mContext.getResources().getDimension(R.dimen.popup_width),
(int)mContext.getResources().getDimension(R.dimen.popup_height), true); // notice that they have to be casted as int
输出
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)