Appending (or extending?) a list of lists

Question:

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)

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]]
Asked By: Honeybee

||

Answers:

First of all, do not use keyword class.

The code you may want is as follows.

result = []
for com in comment:
    record = []
    for c in com:
        record.append(classify_predict(c))
    result.append(record)
Answered By: Gilseung Ahn

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.

Answered By: Selcuk

You can map each sub-list to the classify_predict function:

classifications = [list(map(classify_predict, lst)) for lst in comment]
Answered By: blhsing