如何连接如下列表:
buttons = [[['a','b','c'], '2'], [['d','e','f'], '3']]
到
buttons = [[['a','b','c','2'], ['d','e','f','3']]]
我尝试访问三个索引并连接,但它不起作用:
buttons[0][1]
答案 0 :(得分:7)
一种方法是解压缩列表解析中的每个元素并连接这两个部分:
>>> 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']
答案 1 :(得分:3)
>>> 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']]