Reputation: 1
So, I need to use a for i in loop on a list that is within a list. Let me give you an example.
I have a blacklist (list) that contains 10 categories (also lists), in those categories, there are always 2 ints.
I also have a list called x. x contains 2 ints.
I want to check if the 2 ints inside x are the same as any of the blacklist categories.
In order to do that I need to do
def blacklist_check(blacklist, z):
for i in blacklist:
for y in blacklist[i]:
difference = blacklist[i][y] - z
if difference < 10 and difference > -10:
print(f"{difference} found")
return False
print(f"{difference} not found")
if i == 10:
return True
but when I try that I get
TypeError: list indices must be integers or slices, not list
I can not transfer the categories to ints or any other type than lists. How do I make this work?
Upvotes: 0
Views: 256
Reputation: 7751
If you don't consider the printed statements in the sample code, the simplest way to write it should be to use any
with generator expression:
def blacklist_check(blacklist, z):
return not any(abs(y - z) < 10 for cls in blacklist for y in cls)
This is equivalent to:
def blacklist_check(blacklist, z):
for cls in blacklist:
for y in cls:
if abs(y - z) < 10: # same as -10 < (y - z) < 10
return False
return True
Note that since i
in your code does not represent the index of the element in the blacklist
, you should not judge whether it is the last element by i == 10
, but should directly return True
after the end of the for loop.
Upvotes: 0
Reputation: 178
Here (y) is a list, you cannot nest a list as a index inside another list. Try this
def blacklist_check(blacklist, z):
for i in blacklist:
for y in range(len(i)):
difference = i[y] - z
if difference < 10 and difference > -10:
print(f"{difference} found")
return False
print(f"{difference} not found")
if i == 10:
return True
Upvotes: 1
Reputation: 1237
Python handles for loops differently to perhaps a more conventional C-Type language in that it runs based on enumeration rather than incrementation.
In your case, what you have with for i in blacklist
, for each iteration of the for loop, i
is set to the element rather than the index, so if your data structure looks something like:
[ [1,2,3,4], [5,6,7,8] ]
Then the first value of i
will be [1, 2, 3, 4]
, and is hence a list. If you want the indexes rather than the elements, you could use the range
and len
functions in the following way:
for i in range(len(blacklist)):
which will make i
be 0
on the first iteration, and 1
on the second one, etc.
That would mean that calling blacklist[i]
will return [1, 2, 3, 4]
Upvotes: 0