代码之家  ›  专栏  ›  技术社区  ›  Mainland

Python从n个数字的列表中生成可选数字列表

  •  0
  • Mainland  · 技术社区  · 3 年前

    预期答复:

    num = 14
    grp = 4
    # A list of num natural numbers arranged in group (row) of 4 numbers
    lst = 
    [0,1,2,3,
    4,5,6,7,
    8,9,10,11,
    12,13]
    lst = 
    [[0,1,2,3],
    [4,5,6,7],
    [8,9,10,11],
    [12,13]]
    
    # Reverse elements in odd rows
    newlst = 
    [[0,1,2,3],
    [7,6,5,4], # reversed here
    [8,9,10,11],
    [13,12]]  # reversed here
    # combine elements in all sublists by their position
    # combine first element in all sublists into a new sublist
    sollst = 
    [[0,7,8,13],[1,6,9,12],[2,5,10],[3,4,11]]
    

    我的解决方案:

    num = 14
    grp = 4
    
    #### print
    lst= list(range(0,num,1))
    newlst= [lst[i:i+grp:1] for i in range(0,num,grp)]
    evnlst = newlst[0::2]
    oddlst = newlst[1::2]
    newoddlst = [oddlst [i][::-1] for i in range(len(oddlst))]
    sollst= evnlst + newoddlst 
    # This gives [[0, 1, 2, 3], [8, 9, 10, 11], [7, 6, 5, 4], [13, 12]]
    from itertools import zip_longest    
    print([[x for x in t if x is not None] for t in zip_longest(fevngps)])
    

    目前的答复: 在最终答案之前我已经走到了第一步,现在我不得不把不同长度的列表合并起来,我遇到了一个错误

    TypeError: 'int' object is not subscriptable
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Dani Mesejo    3 年前

    一种方法:

    from itertools import zip_longest
    
    num = 14
    grp = 4
    
    lst = list(range(0, num, 1))
    newlst = [lst[i:i + grp:1] for i in range(0, num, grp)]
    
    # build new list where the sub-list are reversed if in odd indices
    revlst = [lst[::-1] if i % 2 == 1 else lst for i, lst in enumerate(newlst)]
    
    # zip using zip_longest and filter out the None values (the default fill value of zip_longest)
    result = [[v for v in vs if v is not None] for vs in zip_longest(*revlst)]
    print(result)
    

    输出

    [[0, 7, 8, 13], [1, 6, 9, 12], [2, 5, 10], [3, 4, 11]]