简体   繁体   English

Python:使用嵌套的 for 循环生成子列表的索引

[英]Python: Using a nested for loop to produce the index for a sublist

I've got the list student :我有名单student

student = ["test_name","1","6"]

And I've got the read data sublist:我有read data子列表:

read_data = [["test_name","1","2","5","9"],["test_name_2","1","5","2","10"]]

I've written the following nested loop to return the index of a sublist (referred to as x ) in read_data if student[0] == x[0] :如果student[0] == x[0]我已经编写了以下嵌套循环来返回read_data列表(称为x )的索引:

lst = [read_data.index(x) for x in read_data if x[0] == student [0]]

So I'm looping through each item in read data and (if x[0] == student[0] ) the index of the sublist should be stored in lst .所以我遍历读取数据中的每个项目,并且(如果x[0] == student[0] )子列表的索引应该存储在lst

When I try to use this in the index parameter of a list to insert data like so:当我尝试在列表的 index 参数中使用它来插入数据时,如下所示:

read_data[read_data.index(x) for x in read_data if x[0] == student[0]].insert(2,student[0])

I get an error saying generators can't be used for indexes - why not?我收到一条错误消息,说生成器不能用于索引 - 为什么不呢? I can obviously just use the integer stored in lst but this seems inefficient - surely there's a way to do this on one line.我显然可以只使用存储在lst的整数,但这似乎效率低下 - 当然有一种方法可以在一行上做到这一点。

Is there some better alternative method to checking if a string is in any of a read_data 's sublists and getting the index of this sublist?是否有更好的替代方法来检查字符串是否在read_data的任何子列表中并获取该子列表的索引?

In the assignment to lst you are creating a list.在对 lst 的分配中,您正在创建一个列表。 But in the snippet below that, you have merely taken the interior of that list expression and are trying to use it as an index.但是在下面的代码片段中,您只是获取了该列表表达式的内部并尝试将其用作索引。 To fix your specific example, you would need to change:要修复您的特定示例,您需要更改:

read_data[iter_expr]

to:到:

read_data[[iter_expr][0]]

That will use the first value in the list as the index.这将使用列表中的第一个值作为索引。

There are better ways to do this, but this is probably the smallest change that will fix the specific problem you asked about.有更好的方法可以做到这一点,但这可能是解决您询问的特定问题的最小更改。

I dont know why you would want to do this but then you need to put brackets around the list comprehension and get index the first match of it like this:我不知道你为什么要这样做,但是你需要在列表理解周围加上括号,并像这样获取它的第一个匹配项的索引:

read_data[[read_data.index(x) for x in read_data if x[0] == student[0]][0]].insert(2, student[0])

Remember if the list comprehension produces an empty list, you will encounter an IndexError .请记住,如果列表推导式生成一个空列表,您将遇到IndexError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM