【问题标题】:Is there a more efficient way to slice a list out of the center of another list?有没有更有效的方法将一个列表从另一个列表的中心切出?
【发布时间】:2020-04-23 10:34:15
【问题描述】:

我编写这段代码是为了从另一个列表的中心切出一个列表,它似乎可以工作,但我觉得有可能更简洁有效地做到这一点(可能通过列表理解)?

def get_middle(num, val_list):
    idx_val = (int(num/2) , int(num/2 + num%2))
    center_idx = int((len(val_list) - 1)/2)
    idx_one, idx_two = center_idx-idx_val[0], center_idx+idx_val[1] 
    return val_list[idx_one:idx_two]


test_list = [1,2,3,4,5,6,7]
test_num = 3
new_list = get_middle(test_num , test_list )
print(new_list)

以上代码的输出为:[3, 4, 5]

【问题讨论】:

  • [1,2,3,4,5,6] 的预期输出是什么? [3,4,5][2,3,4]?
  • @donkopotamus 预期的输出是[3, 4, 5]

标签: python list list-comprehension slice


【解决方案1】:

是的,你可以在一行中完成。

test_list[len(test_list)//2-test_num//3:len(test_list)//2+test_num//3+1]

当然要根据test_num的奇偶校验和列表长度的奇偶校验做一些调整。

【讨论】:

    【解决方案2】:

    代码:

    def get_middle(num, sequence):
        m = (len(sequence) - 1)//2 - num//2
        return sequence[m:m+num]
    
    
    test_list = [1, 2, 3, 4, 5, 6, 7]
    test_num = 3
    print(get_middle(test_num, test_list))
    

    输出:

    [3, 4, 5]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-28
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 2021-09-05
      • 2012-02-29
      相关资源
      最近更新 更多