Python-如何在Python中串联两个列表?

发布于 2021-02-02 23:23:42

如何在Python中串联两个列表?

例:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

预期结果:

>>> joinedlist
[1, 2, 3, 4, 5, 6]
关注者
0
被浏览
254
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以使用+运算符来组合它们:

    listone = [1,2,3]
    listtwo = [4,5,6]
    
    joinedlist = listone + listtwo
    

    输出:

    >>> joinedlist
    [1,2,3,4,5,6]
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    也可以创建一个生成器,使用来简单地遍历两个列表中的项目itertools.chain()。这使你可以将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表中:

    import itertools
    for item in itertools.chain(listone, listtwo):
        # Do something with each list item
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看