我有一个列表,rods
这是由length
和position
元组的类似项目。 position
始终是一个给定的length
独特。我想找到最频繁的棒长度,然后找出所有唯一(由position
)相邻棒(包括最频繁)出现的总数。细分:总数符合标准的唯一
- 首先我想找到最频繁的杆
length
。 - 然后我想包括所有其他的杆有相邻的
length
通过一些标准(在这个例子中为+ -1),但只有他们有一个唯一的位置 - 不会被认为是(通过'最常见'杆最初的小组,或者通过满足相邻标准添加到该小组中的“新杆”)。 - 并找到这个新的总频率。
我能够通过以下方式来实现这一点,通过排序和使用套,但也许有一个更好的解决方案:
import itertools
#tuples of (length, position)
rods = [(18, 21), (17, 2), (15, 3), (14, 21), (14, 5), (13, 6), (13, 7),
(13, 8), (13, 9), (13, 10), (13, 11), (13, 12), (13, 13), (13, 14),
(13, 15), (13, 16), (13, 17), (13, 18), (13, 19), (13, 20), (13, 21),
(13, 22), (13, 23), (13, 24), (13, 25), (13, 26), (12, 5), (12, 21),
(12, 2)]
lengths = [length for length, position in rods]
#gives tuples of lengths and their frequencies:
length_freq = (sorted([(k,len(list(j))) for k,j in itertools.groupby(sorted(lengths))],
key=lambda x: x[1],reverse=1))
best_length = length_freq[0][0]
#cumulative frequency of rods near best_length, with unique position:
tally = (len(set((best_length,v) for j,v in rods
if best_length - 1 <= j <=best_length + 1)))
print length_freq
#output:
#[(13, 21), (12, 3), (14, 2), (15, 1), (17, 1), (18, 1)]
print tally
#output:
#23
注23
为这个测试数据的正确答案。如同length= 14
两个杆被定位在点也通过杆与length=15
(位置21
,和5
)占用。并且在position=21
处也存在lengths 13 and 12
的重叠。
谢谢,我在2.6这么不幸我不能使用Counter。但是这看起来不错。 – fraxel 2012-04-19 14:38:41