1
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

4 回答 4

5

列出理解来救援!

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

当您想要转换列表中的元素时,列表推导通常是答案。

于 2013-01-04T06:24:38.483 回答
3
some_list = [l + [10, 11] for l in some_list]
于 2013-01-04T06:24:38.533 回答
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]]
于 2013-01-04T06:27:56.840 回答
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)
于 2013-01-04T15:30:36.873 回答