如何在Python中扩展列表中的列表?

时间:2013-01-04 06:22:11

标签: python list nested-lists

some_list = [[1, 2], [3, 4], [5, 6]]

变为

some_list = [[1, 2, 10, 11], [3, 4, 10, 11], [5, 6, 10, 11]]

使用公共列表扩展单个列表(在列表中)(在本例中为[10, 11])。

我想要一种直截了当的方法来做到这一点。

4 个答案:

答案 0 :(得分:5)

列出对救援的理解!

some_list = [l + [10, 11] for l in some_list]

如果要转换列表中的元素,列表推导通常 答案。

答案 1 :(得分:3)

some_list = [l + [10, 11] for l in some_list]

答案 2 :(得分:1)

地图技术

>>> some_list = [[1, 2], [3, 4], [5, 6]]
>>> some_list = map(lambda i : i + [10,11], some_list)
>>> some_list
[[1, 2, 10, 11], [3, 4, 10, 11], [5, 6, 10, 11]]

其他:

>>> some_list = [[1, 2], [3, 4], [5, 6]]
>>> for i in some_list:
...     i.extend([10,11])
... 
>>> some_list
[[1, 2, 10, 11], [3, 4, 10, 11], [5, 6, 10, 11]]

使用切片:

>>> some_list = [[1, 2], [3, 4], [5, 6]]
>>> for i in some_list:
...     i[len(i):] = [10,11]
... 
>>> some_list
[[1, 2, 10, 11], [3, 4, 10, 11], [5, 6, 10, 11]]

答案 3 :(得分:0)

使用以下代码在容器中的每个项目上运行方法并获得结果非常简单:

class Apply(tuple):

    "Create a container that can run a method from its contents."

    def __getattr__(self, name):
        "Get a virtual method to map and apply to the contents."
        return self.__Method(self, name)

    class __Method:

        "Provide a virtual method that can be called on the array."

        def __init__(self, array, name):
            "Initialize the method with array and method name."
            self.__array = array
            self.__name = name

        def __call__(self, *args, **kwargs):
            "Execute method on contents with provided arguments."
            name, error, buffer = self.__name, False, []
            for item in self.__array:
                attr = getattr(item, name)
                try:
                    data = attr(*args, **kwargs)
                except Exception as problem:
                    error = problem
                else:
                    if not error:
                        buffer.append(data)
            if error:
                raise error
            return tuple(buffer)

在您的情况下,您需要编写以下内容以扩展主容器中的每个列表:

some_list = [[1, 2], [3, 4], [5, 6]]
Apply(some_list).extend([10, 11])
print(some_list)