可以一次附加多个列表吗? (蟒蛇)

时间:2013-01-03 00:54:32

标签: python list append

我有一堆列表要添加到单个列表中,这个列表是我正在尝试编写的程序中的“主要”列表。有没有办法在一行代码而不是10代码中执行此操作?我是初学者,所以我不知道......

为了更好地了解我的问题,如果我有这些列表怎么办?

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

并希望将y和z附加到x。而不是做:

x.append(y)
x.append(z)

有没有办法在一行代码中执行此操作?我已经尝试过了:

x.append(y, z)

它不会工作。

7 个答案:

答案 0 :(得分:39)

x.extend(y+z)

应该做你想做的事情

x += y+z

甚至

x = x+y+z

答案 1 :(得分:16)

扩展我的评论

In [1]: x = [1, 2, 3]
In [2]: y = [4, 5, 6]
In [3]: z = [7, 8, 9]
In [4]: from itertools import chain
In [5]: print list(chain(x,y,z))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

答案 2 :(得分:12)

您可以使用带有起始值(空列表)的z-index函数:

sum

如果你想附加任意数量的列表,这尤其适合。

答案 3 :(得分:1)

相当于上述答案,但值得一提的是:

my_map = {
   'foo': ['a', 1, 2],
   'bar': ['b', '2', 'c'],
   'baz': ['d', 'e', 'f'],
} 
list(itertools.chain(*my_map.values()))
['d', 'e', 'f', 'a', 1, 2, 'b', '2', 'c']

在上面的表达式中,*对于将结果作为args链接而言很重要,这与先前的链(x,y,z)相同。另外,请注意结果是哈希排序的。

答案 4 :(得分:1)

如果您更喜欢功能稍强的方法,可以尝试:

@Keyword
    def swipeLeft(){

        TouchAction touch = new TouchAction(getCurrentSessionMobileDriver())
        int device_Height, device_Width
        device_Height = Mobile.getDeviceHeight()
        println device_Height
        device_Width = Mobile.getDeviceWidth()
        println device_Width
        int midheight = device_Height/2
        println midheight
        int midwidth = device_Width/2
        println midwidth
        int startX,startY,endX,endY
        startX = device_Width-100
        startY = midheight
        endX = -startX
        endY = 0
        Mobile.swipe(startX,startY,endX,endY)
        touch.tap(startX, startY).perform()

    }

这使您可以将任意数量的列表连接到列表import functools as f x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] x = f.reduce(lambda x, y: x+y, [y, z], x)

如果您只想将任意数量的列表连接在一起(即不在某些基本列表中),您可以简化为:

x

请注意我们的BFDL对lambdas,reduce和朋友有所保留:https://www.artima.com/weblogs/viewpost.jsp?thread=98196

要完成此答案,您可以在文档中了解有关reduce的更多信息:https://docs.python.org/3/library/functools.html#functools.reduce

我引用:“将两个参数的函数累加到序列项中,从左到右,以便将序列减少为单个值。”

P.S。使用https://stackoverflow.com/a/41752487/532513中描述的import functools as f from operator import add big_list = f.reduce(add, list_of_lists) 非常紧凑,它似乎与列表一起使用,并且非常快(请参阅https://stackoverflow.com/a/33277438/532513)但Python 3.6中的sum()具有以下内容说:

  

此功能专门用于数值,可能会拒绝非数字类型。

虽然这有点令人担忧,但我可能会将其作为连接列表的第一个选项。

答案 5 :(得分:1)

要精确复制append的效果,请尝试以下简单有效的功能:

a=[]
def concats (lists):
    for i in lists:
        a==a.append(i)


concats ([x,y,z])
print(a)

答案 6 :(得分:0)

在一行中,可以通过以下方式完成

x.extend(y+z)

x=x+y+z
相关问题