[英]convert only non-empty list to tuple in a list of lists
how do i convert this: 我怎么转换这个:
[[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
into this: 进入这个:
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
i understand that to convert a tuple into a list, we would simply use list(tuple), or if it is a list like [(1,2),(3,4)] we can use map. 我知道要将元组转换为列表,我们只需使用list(元组),或者如果它是[(1,2),(3,4)]之类的列表,我们可以使用map。 How would i do this with the tuples that are within a list that is inside the main list, while the empty lists remain unchanged? 我如何处理主列表中列表中的元组,而空列表保持不变?
>>> my_list = [[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
>>> [list(*el) for el in my_list]
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
>>> l = [[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
>>> import itertools
>>> [list(itertools.chain(*item)) for item in l]
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
This will also handle multiple tuples per list element (if that's what is desired): 这也将处理每个列表元素的多个元组(如果这是所需的):
>>> l = [[], [], [('ef', 1)], [], [('cd', 3),('ab', 2)]]
>>> [list(itertools.chain(*item)) for item in l]
[[], [], ['ef', 1], [], ['cd', 3, 'ab', 2]]
Something like this: 像这样的东西:
>>> lis = [[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
>>> [list(x[0]) if x else x for x in lis]
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.