我有以下列表列表,其中每个列表由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 notation 和 https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html
但无法找到解决方案。
答案 0 :(得分:0)
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']]