【问题标题】:Python produce alternative numbers list from a list of n numbersPython从n个数字列表中生成替代数字列表
【发布时间】:2021-12-04 10:21:20
【问题描述】:

我有一个包含 n 个数字的列表。我想将它们分组为 g 组。另外,我想反转每个奇数组中的元素。最后,我会将偶数组和奇数组中的所有元素组合成一个新的子列表。首先,我给出我期望的答案以及我出错的地方:

预期答案:

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

【问题讨论】:

    标签: python list numpy sorting arraylist


    【解决方案1】:

    一种方法:

    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]]
    

    【讨论】:

    • 您的解决方案是正确的。该死!我知道我的解决方案很长,而且我正在做回旋处,但存在一种简单的方法。你的解决方案很酷。
    猜你喜欢
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多