So I have a list of lists that contains integers and I want return how many row/lists within it have the numbers 5 and 8 appear two of more times. I have written the following code which logically makes sense to me but it returns 0. Any help would be appreciated.
Output im looking for is 3 since lists 0,2, and 5 have the numbers 5 and 8 appear two of more times.
five_count = 0
eight_count = 0
row_count = 0
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
for list in test:
for num in list:
if(num == 5):
five_count= 1
elif(num == 8):
eight_count= 1
if(five_count >= 2 and eight_count >= 2):
row_count= 1
print(row_count)
CodePudding user response:
You can use list comprehension, and list.count(num)
function which returns no. of times num
occurs in the list
-
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
# if your are interested in only the count of rows
row_count = sum(1 for l in test if l.count(5) >= 2 and l.count(8) >= 2)
print(row_count) # prints 3
# if you want all the indexes where the condition is satisfied
indexes = [ind for ind, l in enumerate(test) if l.count(5) >= 2 and l.count(8) >= 2]
print(indexes) # prints [0, 2, 5]
modifying your code in place, note the
- Use of
=
instead of the incorrect=
- indentation of the
if (five_count >= 2 and eight_count >= 2)
- setting the
five_count
andeight_count
to0
for each list so that we starting counting again from0
-
test =[[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,98,5,5,13,13,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0],
[1,1,5,5,56,5,13,13,6,7,8],
[1,9,5,5,25,5,13,19,6,7,8],
[5,0,5,0,0,0,8,0,8,0,0]
]
row_count = 0
for list in test:
five_count, eight_count = 0, 0
for num in list:
if (num == 5):
five_count = 1
elif (num == 8):
eight_count = 1
print(five_count, eight_count)
if (five_count >= 2 and eight_count >= 2):
row_count = 1
print(row_count) # prints 3
CodePudding user response:
The problem is when you update the counters.
five_count = 1
Set the counter to 1 no matter what. The correct syntax for your need is
five_count = 1