访问嵌套列表中的元素 [英] Accessing elements in a nested list
本文介绍了访问嵌套列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在嵌套列表中有一个名为"train_data"的元素,如示例所示:
I have elements in a nested list called "train_data" like 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]
我想访问前8列的所有行(除了最后一列),以及仅最后一列的所有行.我需要在一行代码中没有for循环.
I would like to access all rows with the first 8 columns (all but the last one), and all rows with only the last column. I need to this without for loops, in a single line of code.
我尝试过这样的事情:
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]
有人可以帮我吗?
对不起,第一个查询的预期输出是:
Sorry, the expected output for the first query 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]
,第二个查询是:
[0]
[0]
[1]
推荐答案
我认为您正在期待
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]
这篇关于访问嵌套列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文