辉煌仪奇 2021-12-10 16:10 采纳率: 46.6%
浏览 116
已结题

python 列表取值求距离

设计一个函数,传入参数 有一个列表,lenglist,给定一个长度y
将其按长度分割为n个列表,每个子列表含y个元素,计算每个子列表最中间元素到子列表每个元素的距离,统计大列表中的子列表中位元素到各个元组的距离个数(相邻元素距离为1 每隔一个距离加一),最后返回一个字典,字典key为距离,value为数量

lenglist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,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

结果

{
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=6
{
1:6,
2:6,
3:3,
}
  • 写回答

5条回答 默认 最新

  • 笨鸟快飞呀 2021-12-10 16:56
    关注
    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 12月21日
  • 已采纳回答 12月16日
  • 修改了问题 12月10日
  • 修改了问题 12月10日
  • 展开全部