1

I have the following list of lists where each list is comprised of 9 elements.

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

I want to remove the last element of the last 2 lists and get:

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

I tried:

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

But this actually keeps the last 2 lists (with 8 elements each)

I reviewed:

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

But could not find a solution.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
Diego
  • 637
  • 3
  • 10
  • 24

1 Answers1

0

ws[-2] is not slicing, it's negative indexing, and it's the next-to-last sub-list in your ws list, here is list slicing:

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

Output:

[['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']]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55