Reputation: 25
hello I want to combine multiple for loops into one loop to make my code less complex. the loop iterates over the elements in a list of lists and add +1 for every correct value.
so let's say i have
ink = 0
mouse = 0
rat = 0
matrix = [
['', 'article1.txt', 'article2.txt', 'article3.txt'], ['ink', 2, 3, 0], ['mouse', 0, 2, 1], ['rat', 0, 0, 1]]
and
for line in matrix[1:2]:
for i in line[1:]:
if i > 0:
ink = ink + 1
for line in matrix[2:3]:
for i in line[1:]:
if i > 0:
mouse = mouse + 1
for line in matrix[3:4]:
for i in line[1:]:
if i > 0:
rat = rat + 1
I'd want this to become one loop or atleast some shorter code that automatically does this, even if there would be more rows and columns in the matrix.
Upvotes: 1
Views: 95
Reputation: 10961
One way to improve your code, would be:
>>> d = {}
>>> for row in matrix[1:]:
d[row[0]] = len(list(filter(lambda x: x>0, row[1:])))
>>> d
{'ink': 2, 'mouse': 2, 'rat': 1}
This also could be compacted into one liner dictionary comprehension:
>>> d = {row[0]:len(list(filter(lambda x: x>0, row[1:]))) for row in matrix[1:]}
Upvotes: 3
Reputation: 744
So assuming a correct value is a value greater than 1, i did this: Also to have infinite values, i organized the results in a dictionary:
matrix = [
["", "article1.txt", "article2.txt", "article3.txt"],
["ink", 2, 3, 0],
["mouse", 0, 2, 1],
["rat", 0, 0, 1]]
results = {product[0]: [1 for a in product[1:] if a > 0].count(1) for product in matrix[1:]}
print(results)
I hope this is what you expected. Let me know if you need any adjustments or explanations. This would be the result for your example:
{'ink': 2, 'mouse': 2, 'rat': 1}
Upvotes: 3