大家好,我有以下代码:
from math import sqrt
array = [(1,'a',10), (2,'a',11), (3,'c',200), (60,'a',12), (70,'t',13), (80,'g',300), (100,'a',305), (220,'c',307), (230,'t',306), (250,'g',302)]
def stat(lst):
"""Calculate mean and std deviation from the input list."""
n = float(len(lst))
mean = sum([pair[0] for pair in lst])/n
## mean2 = sum([pair[2] for pair in lst])/n
stdev = sqrt((sum(x[0]*x[0] for x in lst) / n) - (mean * mean))
## stdev2 = sqrt((sum(x[2]*x[2] for x in lst) / n) - (mean2 * mean2))
return mean, stdev
def parse(lst, n):
cluster = []
for i in lst:
if len(cluster) <= 1: # the first two values are going directly in
cluster.append(i)
continue
###### add also the distance between lengths
mean,stdev = stat(cluster)
if (abs(mean - i[0]) > n * stdev): # check the "distance"
yield cluster
cluster[:] = [] # reset cluster to the empty list
cluster.append(i)
yield cluster # yield the last cluster
for cluster in parse(array, 7):
print(cluster)
它的作用是通过查看变量 i[0] 将我的元组列表(数组)聚集在一起。我还想实现的是进一步通过变量 i[2] 在我的每个元组中对其进行聚类。
当前输出为:
[(1, 'a', 10), (2, 'a', 11), (3, 'c', 200)]
[(60, 'a', 12), (70, 't', 13), (80, 'g', 300), (100, 'a', 305)]
[(220, 'c', 307), (230, 't', 306), (250, 'g', 302)]
我想要这样的东西:
[(1, 'a', 10), (2, 'a', 11)]
[(3, 'c', 200)]
[(60, 'a', 12), (70, 't', 13)]
[(80, 'g', 300), (100, 'a', 305)]
[(220, 'c', 307), (230, 't', 306), (250, 'g', 302)]
所以 i[0] 的值很接近,而且 i[2] 也很接近。任何想法如何破解它?