Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending (or extending?) a list of lists

So here’s a list of lists:

comment = [['a', 'b', 'c'],
           ['d', 'e', 'f', 'g'],
           ['h']]

Say there’s a function classify_predict that classifies each element of comment to either 0, 1, or 2.

class = []

for i in range(0, len(comment))
    for j in range(0, len(comment[i]))
        result = classify_predict(comment[i][j])
        class.append(result)

What I’m getting: then the result is just a list (so not corresponding to comment)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(class)

[0, 1, 0, 1, 1, 1, 1, 1]

What I want to get: What should I do to get the next result?

print(class)

[[0, 1, 0],
 [1, 1, 1, 1],
 [1]]

>Solution :

Try creating an intermediate list to store the results for the sub-lists:

results = []

for i in range(0, len(comment))
    result = []
    for j in range(0, len(comment[i]))
        result.append(classify_predict(comment[i][j]))
    results.append(result)

or in a single line, using nested list comprehensions:

results = [[classify_predict(item) for item in sublist] for sublist in comment]

As a side note, don’t use built-ins (such as class) as variable names.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading