可以一次扩展两个列表吗? [英] Possible to extend two lists at once?

查看:58
本文介绍了可以一次扩展两个列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表(列表_1,列表_2)和一个返回两个列表(列表_1_f,列表_2_f)的函数,我想将列表_1_f的项目添加到列表_1,将列表_2_f的项目添加到列表_2:

I have two lists (list_1,list_2) and a function which returns two lists (list_1_f, list_2_f) and I would like to add the items of list_1_f to list_1 and the items of list_2_f to list_2:

def lists():
    list_1_f = [10,10,10]
    list_2_f = [20,20,20]    
    return list_1_f,list_2_f

list_1, list_2 = [1,1,1], [2,2,2]

这种情况是,我总是有2个原始列表,而扩展将仅用于另外两个列表.这样一来,最后我将有两个包含原始项目的列表以及从函数中获得的列表,输出将是:

The case is that I always have 2 original lists and the extension is going to be done just for another two extra lists. So that at the end I would have two lists with the original items plus the ones got from the function, and the output would be:

list_1 = [1,1,1,10,10,10]
list_2 = [2,2,2,20,20,20]

我已经尝试过使用扩展功能执行以下几行,但均无效:

I have tried the following lines using extend function but none works:

list_1.extend([]), list_2.extend([]) = lists()
list_1.extend(), list_2.extend() = lists()
list_1.extend, list_2.extend = lists()

我总是可以执行以下操作:

I could always do the following:

list_1a, list_2a = lists()
list_1.extend(list_1a)
list_2.extend(list_2a)

但是我想知道是否有可能在不创建两个中间列表的情况下进行扩展.

But I was wondering if it is even possible to make the extension without having to create two intermediate lists.

推荐答案

这不可能直接实现,因为赋值左侧必须是函数调用.它只能由简单变量,数据成员,下标和逗号,括号或方括号构成.

It is not directly possible, because what must be on the left side of an assignment cannot be a function call. It can only be built from simple variables, data members, subscripts and commas, parentheses or square brackets.

最好的方法是在右侧使用理解或地图:

Best that can be done is to use a comprehension or a map on the right side:

list_1, list_2 = map(lambda x: sum(x, []), zip((list_1, list_2), lists()))

(感谢@meowgoesthedog这样)

(thanks to @meowgoesthedog for that way)

使用3行的清晰代码是否更好取决于读者.恕我直言,唯一真正的用例是在仅支持唯一表达式的lambda内部

Whether it is better that a clear code using 3 lines is up to the reader. IMHO the only real use case would be inside a lambda which only supports a unique expression

这篇关于可以一次扩展两个列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆