python 列表取值求距离??
课程设计
1
设计一个函数,传入参数 有一个列表,lenglist,给定一个长度y 将其按长度分割为n个列表,每个子列表含y个元素,计算每个子列表最中间元素到子列表每个元素的距离,统计大列表中的子列表中位元素到各个元组的距离个数(相邻元素距离为1 每隔一个距离加一),最后返回一个字典,字典key为距离,value为数量
lenglist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1 7,18]
y=9
p=func(lenglist,y)
print(p)
#打印内容为
{
1:4,
2:4,
3:4,
4:4,
}
测试数据为
lenglist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
y=9
-
def func(lenglist, y): res = [] tmp = [] for i in range(len(lenglist)): # 拆分成子列表 if not i == 0 and i % y == 0: res.append(tmp.copy()) tmp.clear() tmp.append(lenglist[i]) else: tmp.append(lenglist[i]) res.append(tmp) resmap = {} for datalist in res: lens = len(datalist) if lens % 2 == 0: # 子列表长度为偶数 index_mid = int(lens/2) for j in range(index_mid): if j+1 not in resmap.keys(): if j == index_mid-1: resmap[j + 1] = 1 else: resmap[j + 1] = 2 else: if j == index_mid-1: resmap[j + 1] += 1 else: resmap[j + 1] += 2 else: # 子列表长度为奇数 index_mid = int((lens - 1)/2) # 奇数 for j in range(index_mid): if j+1 not in resmap.keys(): resmap[j+1] = 2 else: resmap[j+1] += 2 return resmap lenglist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] y = 6 p = func(lenglist, y) print(p)
-
def func(array, k): # 根据k来划分原来的列表 new_array = [] new_dict = {} pre = 0 for i in range(len(array)): if (i + 1) % k == 0: new_array.append(array[pre:i + 1]) pre += k if pre < len(array): new_array.append(array[pre:]) # 将分离后的新列表映射成索引列表(二维) index_array = [] for i in range(len(new_array)): new = [] for j in range(len(new_array[i])): new.append(j + 1) index_array.append(new) for i in range(len(index_array)): the_array = index_array[i] min_index = int(len(the_array) / 2) for j in range(len(the_array)): if j == min_index: continue else: new_dict[abs(the_array[min_index] - the_array[j])] = new_dict.get( abs(the_array[min_index] - the_array[j]), 0) + 1 return new_dict if __name__ == '__main__': lenglist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] p = func(lenglist, 9) q = func(lenglist, 6) print('k为9:', p) print('k为6:', q)
发表回复