【问题标题】:Concatenate list and number in a sublist in Python [duplicate]在Python中的子列表中连接列表和数字[重复]
【发布时间】:2015-09-24 21:36:56
【问题描述】:

如何连接这样的列表:

buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]

进入

buttons = [[['a','b','c','2'], ['d','e','f','3']]]

我尝试访问三个索引并连接,但没有成功:

buttons[0][1]

【问题讨论】:

    标签: python list


    【解决方案1】:

    一种方法是将列表理解中的每个元素解包并连接两个部分:

    >>> buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]
    >>> [x + [y] for x, y in buttons]
    [['a', 'b', 'c', '2'], ['d', 'e', 'f', '3']]
    

    这是可行的,因为每个子列表都有两个元素;第一个元素分配给x,第二个元素分配给y。例如,对于buttons 中的第一个子列表,我们有:

    x, y = [['a','b','c'], '2']
    

    那么:

    >>> x
    ['a','b','c']
    >>> y
    '2'
    

    这两个部分然后像这样连接在一起:

    x + [y] == ['a', 'b', 'c'] + ['2'] == ['a', 'b', 'c', '2']
    

    【讨论】:

    • 这很好很优雅!
    • 有人能解释一下这是如何工作的吗?我不明白你怎么样['2'] and ['3']
    • @SirParselot:添加了对该方法的说明。
    【解决方案2】:
    >>> import itertools
    >>> l = [[['a','b','c'], '2'], [['d','e','f'], '3']]
    >>> [list(itertools.chain.from_iterable(i)) for i in l]
    [['a', 'b', 'c', '2'], ['d', 'e', 'f', '3']]
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 2019-06-30
      • 2021-09-08
      • 1970-01-01
      • 2011-03-02
      • 1970-01-01
      相关资源
      最近更新 更多