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,
}
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)

结果

img


可以将分离后的列表映射到索引列表上,这样距离就是索引相减的值,有用的话点一下采纳

def func(lenglist,y):
    new_list=[]
    if len(lenglist)<y:pass
    else:
        j=0
        for i in range(1,len(lenglist)+1):            
            if i%y==0:
                new_list.append(lenglist[j:i])
                j=i

        if j!=len(lenglist) :new_list.append(lenglist[j:len(lenglist)])
        
    dict1={}
    print(new_list)
#     a=len(new_list)//2        #大列表
#     for i in range(len(new_list)):                
#         if abs(a-i) not in dict1.keys():dict1[abs(a-i)]=1
#         else:dict1[abs(a-i)]+=1
    for i in range(len(new_list)):         #小列表
        b=len(new_list[i])//2
        for j in range(len(new_list[i])):            
            if abs(b-j) not in dict1.keys():dict1[abs(b-j)]=1
            else:dict1[abs(b-j)]+=1
    del dict1[0]
    print(dict1)
            
lenglist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
y=9
func(lenglist,y)


太难受了,本来想偷个懒的,思路,先将数组按长度分割,转换成二维数组
随后计算中位数,用循环遍历子列表计算长度,长度计算,通过中位 index- 遍历的index即可 不计算自己,价格if 跳过,有更好的方法的更快实现的可以继续在下面给答案,我会采纳的,下面是我自己的方法



def cut_list(lists: list, cut_len: int) -> [[int]]:
    """
    将列表拆分为指定长度的多个列表
    :param lists: 初始列表
    :param cut_len: 每个子列表的长度
    :return:[[int]]
    """
    res_data = []
    if len(lists) > cut_len:
        for i in range(int(len(lists) / cut_len)):
            cut_a = lists[cut_len * i:cut_len * (i + 1)]
            res_data.append(cut_a)

        last_data = lists[int(len(lists) / cut_len) * cut_len:]
        if last_data:
            res_data.append(last_data)
    else:
        res_data.append(lists)
    return res_data


def Calculationlength(lists: [[int]]) -> {int: int}:
    """
    计算子列表中间元素到各元素的距离
    :param lists: 待计算二维列表
    :return:{int:int}
    """
    tempdict = {}
    for i in lists:
        center_index = math.ceil(len(i) / 2)
        for j in range(len(i)):
            if center_index != (j + 1):
                distance = abs(center_index - j - 1)
                if tempdict.get(distance):
                    tempdict[distance] += 1
                else:
                    tempdict[distance] = 1

    return tempdict

运行效果

img

看看这个拆分

import more_itertools as mi

lenglist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
res = mi.grouper(lenglist, 9)
print(list(res))