1

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.

1
  • for row in matrix[1:]: for col in row[1:]: ... Commented Feb 6, 2021 at 11:13

2 Answers 2

3

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}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this works and I am able to understand! Thanks
3

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

3 Comments

Great so upvoted, but also could have d as a dict comprehension i.e.: d = {row[0]:len(list(filter(lambda x: x>0, row[1:]))) for row in matrix[1:]}
@DarrylG, true, I just wanted to stick to OP code to show him how he can improve his, but I'll add your comment in the answer as well
@IronFist--understood. Sort of an interesting code golf problem with even shorter solutions such as d = {row[0]:sum(x>0 for x in row[1:]) for row in matrix[1:]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.