Access items in a nested list

I have items in a nested list called "train_data", as in the example:

[0] [0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[1] [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
[2] [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]

I would like to access all rows with the first 8 columns (all but the last), and all rows with only the last column. I need this without loops, in one line of code.

I tried something like this:

print train_data[0][:]
print train_data[:][0]

but this gives me the same result:

[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]

Can anyone help me?

Edit:

Sorry, the expected output for the first request is:

[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494]
[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675]
[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]

and for the second request:

[0]
[0]
[1]
0
source share
3 answers

I think you expect it

L1 = [x[0:-1] for x in train_data]
L2 = [x[-1] for x in train_data]

for x in L1:
    print x

for x in L2:
    print [x]
+1
source

you can use slice [:-1]to get all elements except the last!

>>> l1=[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
>>> l2=[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
>>> l3=[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]
>>> l=[l1,l2,l3]
>>> [i[:-1] for i in l]
[[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494], [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675], [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]]
+3

oneliner? , ?

print [i[:-1] for i in l]  # All rows with all cols - 1
print [i[-1] for i in l]  # All rows with last col

But even if the loop is not explicit with for, it is implied as a complete list ...

edit: 1 → -1 for the second line of code, my mistake

+2
source

Source: https://habr.com/ru/post/1624206/


All Articles