Reputation: 65
I have a linked list with the following values:
switch_list = [[4, 1, 2, 2],
[4, 2, 3, 2],
[3, 1, 1, 3],
[3, 2, 4, 2],
[1, 3, 3, 1],
[1, 2, 2, 1],
[2, 1, 1, 2],
[2, 2, 4, 1]]
My goal is to compare an integer with the first value of the all linked-list and then, return a new list with filtered values.
Example: I want all values in switch_list with the first number equals 4, then the function will returns:
[[4, 1, 2, 2], [4, 2, 3, 2],]
Here is my program:
def bucket(value, input):
output = []
for i in input:
if i[0][0] == value:
output.append(i)
return output
And here is the output error:
File "matrix_optimizate.py", line 63, in bucket
if i[0][0] == value:
TypeError: 'int' object has no attribute '__getitem__'
Upvotes: 1
Views: 55
Reputation: 357
I am assuming that input
is going to be your list of lists. In that case,
for i in input:
will give you each sub list as i
during each iteration. By trying to access
i[0][0]
you are trying to access the first element of the element of the sublist. In your example
i
would give [4, 1, 2, 2]
i[0]
would give 4
, andi[0][0]
would therefore not make sensePlease try i[0]
instead.
Edit: Please note that this answer only serves to point out your current problem. dursk's answer provides other solutions to what you are trying to perform as a whole and those options are much more powerful (list comprehension is a fantastic tool, I would recommend looking into it).
Upvotes: 3
Reputation: 4445
You're already iterating over the outer list, so there's no need for two index lookups.
for i in input:
if i[0] == value:
output.append(i)
Also, there's a much more elegant way to do this using filter
:
def bucket(input, value):
return filter(lambda x: x[0] == value, input)
At which point you probably don't even need to have it as it's own function.
And lastly you could use a list comprehension as well:
[i for i in input if i[0] == value]
Upvotes: 3