开发者

Appending Nested Lists in Python

I have the following question for homework

Define a function append lists that takes a list of lists and returns a new list containing the sublist values. For example, append lists([[1, 2], [3, 4], [5]]) should return the list [1, 2, 3, 4, 5] and append lists([[1, 2], [3], [[4, 5]]]) should return the list [1, 2, 3, [4, 5]].

I've tried various ways of creating this function in order to append the list so it gives the desired output to no avail so I came here looking for some help. I've found a few other ways of going about this online, but they use extensive methods that we haven't even dabbled in as of yet in my CPSC 121 class. We're limited to the basics in wha开发者_如何学JAVAt we've learned.

Any help would be much appreciated!


By now, it is likely that the assignment is gone, but here is a solution:

def append_lists(lists):
    output = []
    for l in lists:
        for e in l:
            output.append(e)
    return output

This appends each element of each list to the output of the function, which eliminates exactly one level of nesting in the elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜