简体   繁体   中英

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

I've got the list student :

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

And I've got the read data sublist:

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

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 .

When I try to use this in the index parameter of a list to insert data like so:

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.

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?

In the assignment to lst you are creating a list. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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