我已经看到了以下代码片段:
func getValue(idx: Int)->string {
if arrayValue.count <= 0 {
callbackfunc() { [weak self] arrayValue in
DispatchQueue.main.async {
self.processReturnedData(arrayValue[idx])
}
}
} else {
return arrayValue[idx]
}
}
func processReturnedData(_ idx: IDXType) {
//do something with the data
}
因此它遍历列表并计算转换次数,例如# list representing sequence of states
states = ['a','b','c','d','a','a','a','b','c','b','b','b']
# matrix of transitions
M = {}
for i in range(len(states)-1):
M.setdefault((states[i], states[i+1]), [0])[0] += 1
,a->b
,b->c
等。我知道如果密钥不在字典中,c->c
将插入默认值。但是我不明白为什么默认值是列表本身,在这种情况下,它是[0]。同样,setdefault()
意味着我们总是选择列表的第一个元素并将其递增。
采用这种方法的原因可能是什么?
答案 0 :(得分:1)
按照您的理解,它可以工作-关于为什么使用列表值而不是直接使用整数的原因-它不能使用“纯”整数和setdefault(..)
。
原因:setdefault()
返回此键的字典值。如果返回列表,则会得到对该列表的引用。如果您修改列表,则更改将反映在字典中(因为:参考)。如果使用整数,则返回该整数,但是对其进行修改不会更改分配给该字典内部键的值。
# list representing sequence of states
states = ['a','b','c','d','a','a','a','b','c','b','b','b']
# matrix of transitions
M = {}
for i in range(len(states)-1):
M.setdefault((states[i], states[i+1]), [0])[0] += 1
print(M)
输出:
{('a', 'b'): 2, ('b', 'c'): 2, ('c', 'd'): 1, ('d', 'a'): 1,
('a', 'a'): 2, ('c', 'b'): 1, ('b', 'b'): 2}
如果您想不使用包含单个计数器整数的列表,则可以执行以下操作:
for i in range(len(states)-1):
# does not work, error: M.setdefault((states[i], states[i+1]), 0) += 1
M.setdefault((states[i], states[i+1]), 0)
M[(states[i], states[i+1])] += 1
print(M)
输出:
{('a', 'b'): 2, ('b', 'c'): 2, ('c', 'd'): 1, ('d', 'a'): 1,
('a', 'a'): 2, ('c', 'b'): 1, ('b', 'b'): 2}
但这需要两行-您不能直接分配给整数。
我个人可能会这样做:
# list representing sequence of states
states = ['a','b','c','d','a','a','a','b','c','b','b','b']
# matrix of transitions
from collections import defaultdict
M = defaultdict(int)
for a, b in zip(states,states[1:]):
M[(a,b)] += 1
print(dict(M)) # or use M directly - its str-output is not that nice though
与使用基础字典setdefault
相比,它应该性能更高。