【问题标题】:How to convert multiple list of list into list?如何将多个列表列表转换为列表?
【发布时间】:2020-06-29 18:19:19
【问题描述】:

我的数据如下:

import pandas as pd
df2 = pd.DataFrame([[ "I am new at programming."],
                   [ "Leaves are falling from tree."]], columns = ['Text'])

输入文件打印:

    Text
0   I am new at programming.
1   Leaves are falling from tree.

我有一个执行 NLP 任务的代码:

NewListA = []

for inputs in df2['Text']:
    t = nlp(inputs)
    res_A = {}
    for sent in t.sentences:
        for word in sent.words:
            # append to dict
            txt= f'{word.text}'
            upos= f'{word.upos}'
            res_A[txt]= upos

    NewList = list(res_A.items())            
    NewListA.append(NewList)

输出为:

[[('I', 'PRON'), ('am', 'AUX'), ('new', 'ADJ'), ('at', 'ADP'), ('programming', 'NOUN'), ('.', 'PUNCT')], [('Leaves', 'NOUN'), ('are', 'AUX'), ('falling', 'VERB'), ('from', 'ADP'), ('tree', 'NOUN'), ('.', 'PUNCT')]]

这会产生一个额外的最外面的列表括号。我想删除最外面的括号并得到:

[('I', 'PRON'), ('am', 'AUX'), ('new', 'ADJ'), ('at', 'ADP'), ('programming', 'NOUN'), ('.', 'PUNCT')], [('Leaves', 'NOUN'), ('are', 'AUX'), ('falling', 'VERB'), ('from', 'ADP'), ('tree', 'NOUN'), ('.', 'PUNCT')]

我可以将其转换为数据框并最终得到:

    POS
0   [('I', 'PRON'), ('am', 'AUX'), ('new', 'ADJ'), ('at', 'ADP'), ('programming', 'NOUN'), ('.', 'PUNCT')]
1   [('Leaves', 'NOUN'), ('are', 'AUX'), ('falling', 'VERB'), ('from', 'ADP'), ('tree', 'NOUN'), ('.', 'PUNCT')]

我查看了 this solutionthis 但是,这些删除了列表中的所有括号,这不是我要找的。​​p>

注意:我的愿望结果示例是:

[['A','B'],['B','C']] --> ['A','B'],['B','C']

【问题讨论】:

  • 你能给出预期的结果吗?
  • @AnnZen 谢谢。我刚刚更新了
  • @Bilgin 你确定你的代码有问题吗?删除最外面的括号不会对您的代码产生有意义的影响(请参阅下面的答案),并且您提供的示例应该已经生成了您想要的数据框。
  • @Bilgin 完美。我添加了一个答案,

标签: python pandas


【解决方案1】:

无需删除括号即可产生您想要的结果:

import pandas as pd

NewListA = [[('I', 'PRON'), ('am', 'AUX'), ('new', 'ADJ'), ('at', 'ADP'), ('programming', 'NOUN'), ('.', 'PUNCT')], [('Leaves', 'NOUN'), ('are', 'AUX'), ('falling', 'VERB'), ('from', 'ADP'), ('tree', 'NOUN'), ('.', 'PUNCT')]]

df = pd.DataFrame({'POS':NewListA})
print(df)

独立于NewListA的大小,您可以通过管理df的行来管理每个列表。

【讨论】:

  • 感谢您的回答,但列表的大小发生了变化。就像现在我有两个列表,但这可以改变,我不想写成:lst1,lst2,...
【解决方案2】:

如果您从NewListA 中删除最外面的括号,结果将是一个隐式元组,其行为应该与您代码中的列表相同。

示例

[list1, list2, list3] 是一个包含三个列表的列表。

list1, list2, list3 等价于(list1, list2, list3),是一个三元组。

【讨论】:

  • 感谢 cmets。您的意思是将列表保存到最后的元组而不是列表中吗?
  • @Bilgin 元组列表和列表列表在您的情况下是等效的。您的代码可能没有问题,如others have suggested
【解决方案3】:

您正在使用二维数组 (NewListA),


使用NewListA[0] 获取:

[('I', 'PRON'), ('am', 'AUX'), ('new', 'ADJ'), ('at', 'ADP'), ('programming', 'NOUN'), ('.', 'PUNCT')]

使用NewListA[1] 获取:

[('Leaves', 'NOUN'), ('are', 'AUX'), ('falling', 'VERB'), ('from', 'ADP'), ('tree', 'NOUN'), ('.', 'PUNCT')]

【讨论】:

  • 感谢您的回答,但我的输入大小发生了变化。对于存储元素或摆脱最外层的括号,您还有其他建议吗?
猜你喜欢
  • 2019-10-18
  • 2011-12-26
  • 2017-12-19
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2022-01-24
  • 2016-11-30
相关资源
最近更新 更多