【问题标题】:Remove last element of the last two lists of a list of lists删除列表列表的最后两个列表的最后一个元素
【发布时间】:2018-03-10 15:48:03
【问题描述】:

我有以下列表,其中每个列表由 9 个元素组成。

ws = [['1.45', '1.04', '1.13', '2.01', '1.46', '1.22', '1.30', '2.60', '2.19'], ['1.71', '1.13', '1.21', '2.07', '1.53', '1.27', '1.47', '2.82', '2.43'], ['1.36', '0.99', '1.03', '1.93', '1.39', '1.14', '1.23', '2.45', '2.06'], ['1.88', '3.24', '1.97', '1.38', '1.67', '3.22', '2.02', '1.57', '1.86'], ['1.95', '3.32', '2.03', '1.44', '1.71', '3.43', '2.14', '1.64', '1.93'], ['1.82', '3.12', '1.88', '1.34', '1.59', '3.14', '1.94', '1.50', '1.80']]

我想删除最后 2 个列表的最后一个元素并得到:

[['1.45', '1.04', '1.13', '2.01', '1.46', '1.22', '1.30', '2.60', '2.19'], ['1.71', '1.13', '1.21', '2.07', '1.53', '1.27', '1.47', '2.82', '2.43'], ['1.36', '0.99', '1.03', '1.93', '1.39', '1.14', '1.23', '2.45', '2.06'], ['1.88', '3.24', '1.97', '1.38', '1.67', '3.22', '2.02', '1.57', '1.86'], ['1.95', '3.32', '2.03', '1.44', '1.71', '3.43', '2.14', '1.64'], ['1.82', '3.12', '1.88', '1.34', '1.59', '3.14', '1.94', '1.50']]

我试过了:

ws_sliced = [l[0:8] for l in ws[-2]]

但这实际上保留了最后 2 个列表(每个列表有 8 个元素)

我评论过:

Explain slice notationhttps://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html

但找不到解决办法。

【问题讨论】:

    标签: python python-2.7 slice


    【解决方案1】:

    ws[-2] 不是切片,它是负索引,它是您的 ws 列表中的倒数第二个子列表,这里是列表切片:

    ws = [['1.45', '1.04', '1.13', '2.01', '1.46', '1.22', '1.30', '2.60', '2.19'],
          ['1.71', '1.13', '1.21', '2.07', '1.53', '1.27', '1.47', '2.82', '2.43'],
          ['1.36', '0.99', '1.03', '1.93', '1.39', '1.14', '1.23', '2.45', '2.06'],
          ['1.88', '3.24', '1.97', '1.38', '1.67', '3.22', '2.02', '1.57', '1.86'],
          ['1.95', '3.32', '2.03', '1.44', '1.71', '3.43', '2.14', '1.64', '1.93'],
          ['1.82', '3.12', '1.88', '1.34', '1.59', '3.14', '1.94', '1.50', '1.80']]
    
    # ws[:-2] => Slice ws from the first sub-list to the one before the next-to-last
    # [ws[-2], ws[-1]] => The last and next-to-last sub-lists
    ws_sliced = ws[:-2] + [l[0:8] for l in [ws[-2], ws[-1]]]
    print ws_sliced
    

    输出:

    [['1.45', '1.04', '1.13', '2.01', '1.46', '1.22', '1.30', '2.60', '2.19'],
     ['1.71', '1.13', '1.21', '2.07', '1.53', '1.27', '1.47', '2.82', '2.43'],
     ['1.36', '0.99', '1.03', '1.93', '1.39', '1.14', '1.23', '2.45', '2.06'],
     ['1.88', '3.24', '1.97', '1.38', '1.67', '3.22', '2.02', '1.57', '1.86'],
     ['1.95', '3.32', '2.03', '1.44', '1.71', '3.43', '2.14', '1.64'],
     ['1.82', '3.12', '1.88', '1.34', '1.59', '3.14', '1.94', '1.50']]
    

    【讨论】: