我有一个2D arraylist数据填充这样的循环:
data.append([TrueID,rssi])
8次后,我获得了数据的这个值:
data =
[['469420270013002A', -90],
['469420270005000C', -89],
['469420270013002A', -94],
['4694202700270003', -53],
['469420270005000C', -91],
['469420270013002A', -92],
['4694202700270003', -55]]
我想计算每个TrueID的平均RSSI值,并返回其最低RSSI值及其TrueID。
所以我需要输出:
print "The weakest ID is " ID_result " with Rssi value of " rssi_result
>>The weakest ID is '4694202700270003' with Rssi value of -54
2D阵列必须填充到20个值,并像FIFO系统一样继续。
欢迎所有建议(即使您知道获得相同结果的其他方法)!
谢谢!
答案 0 :(得分:1)
使用collections.defaultdict
和max
:
>>> from collections import defaultdict
>>> lis = [['469420270013002A', -90],
['469420270005000C', -89],
['469420270013002A', -94],
['4694202700270003', -53],
['469420270005000C', -91],
['469420270013002A', -92],
['4694202700270003', -55]]
>>> d = defaultdict(list)
>>> for k, v in lis:
d[k].append(v)
...
现在d
包含:
>>> d
defaultdict(<type 'list'>,
{'469420270005000C': [-89, -91],
'4694202700270003': [-53, -55],
'469420270013002A': [-90, -94, -92]})
现在使用max
和字典理解来计算平均值并找出最大(键,值)对:
>>> max({k:sum(v)/float(len(v)) for k, v in d.items()}.items(), key=lambda x:x[1])
('4694202700270003', -54.0)