简体   繁体   English

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

[英]How do I extend a list within a list in Python?

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

becomes 变成

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

extending the individual lists (within a list) with a common list (in this case [10, 11] ). 用公共列表(在这种情况下[10, 11] )扩展单个列表(在列表内)。

I want a straightforward way to do this. 我想要一个简单的方法来做到这一点。

List comprehensions to the rescue! 列出对救援的理解!

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

When you want to transform the elements in a list, a list comprehension is usually the answer. 当您要转换列表中的元素时,列表理解通常是答案。

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

Map technique: 地图技术:

>>> 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]]

Other: 其他:

>>> 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]]

Using slicing: 使用切片:

>>> 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]]

Running a method on each item in a container and getting results is rather easy with the following code: 使用以下代码,在容器中的每个项目上运行方法并获得结果非常容易:

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)

In your case, you would want to write the following to extend each of the lists in your main container: 对于您的情况,您需要编写以下内容以扩展主容器中的每个列表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM