如何在子字符串处拆分嵌套列表?

时间:2018-12-20 19:39:33

标签: python list

a = [['dog===frog', 'cat===dog'], ['bird===bat', 'ball===call']]

len(a)可以根据需要增大,而len(a[I])可以根据需要增大。.

我怎样才能离开b = [['dog','frog','cat','dog'],['bird','bat','ball','call']]

我尝试了类似的方法

[' '.join(x).split('===') for x in new_list]

和.join只是一般的列表理解,但是没有运气。

6 个答案:

答案 0 :(得分:1)

b = [sum([x.split('===') for x in sublist], []) for sublist in a]

应该给您您想要的。像这样工作:

  • split('===')从每个字符串中列出列表
  • 然后,您使用总和添加它们:sum([['dog', 'frog'], ['cat', 'dog']], [])基本上是['dog', 'frog'] + ['cat', 'dog']
  • sum([x.split('===') for x in sublist], [])使用list comprehension从所有小列表(['dog===frog', 'cat===dog'])中创建一个拆分列表,将其馈送到sum
  • 所有内容都包含在另一种理解中,可以针对您的大列表a

答案 1 :(得分:1)

您可以使用nested list comprehension

a = [['dog===frog', 'cat===dog'], ['bird===bat', 'ball===call']]
result = [[chunk for chunks in map(lambda e: e.split('='), sub) for chunk in chunks if chunk] for sub in a]
print(result)

输出

[['dog', 'frog', 'cat', 'dog'], ['bird', 'bat', 'ball', 'call']]

答案 2 :(得分:1)

您可以使用chain.from_iterable来将将列表中的字符串拆分为单个列表的结果变平整。

from itertools import chain

[list(chain.from_iterable(s.split('===') for s in sub)) for sub in a]
# [['dog', 'frog', 'cat', 'dog'], ['bird', 'bat', 'ball', 'call']]

答案 3 :(得分:1)

这是使用列表理解的一线工具。

[[word for element in sublist for word in element.split('===')] for sublist in a]

答案 4 :(得分:1)

import numpy as np
a = [['dog===frog', 'cat===dog'], ['bird===bat', 'ball===call']]
a = [ i.split('===') for i in np.array(a).ravel()]

输出:

[['dog', 'frog'], ['cat', 'dog'], ['bird', 'bat'], ['ball', 'call']]

答案 5 :(得分:1)

def flatten(seq):
    """list -> list                                                                                                                                                                           
    return a flattend list from an abitrarily nested list                                                                                                                                     
    """
    if not seq:
        return seq
    if not isinstance(seq[0], list):
        return [seq[0]] + flatten(seq[1:])
    return flatten(seq[0]) + flatten(seq[1:])

b=[[j.split("===") for j in i] for i in a]
c=[flatten(i) for i in b]
c
    [['dog', 'frog', 'cat', 'dog'], ['bird', 'bat', 'ball', 'call']]