【问题标题】:Appending lists to a new list in python as objects将列表作为对象附加到python中的新列表
【发布时间】:2017-12-22 05:21:30
【问题描述】:

将 mongoengine 数据库作为列表查询我想将它们附加到可迭代的新列表中。我当前的代码:

data=[]
other_doc = Document.objects(bank="boe_dd4a95f6ec1c41ba47239fe6fd688b8cc1232c3d25a68b76836172d99164cb82")
data.append(other_doc)
other_doc_1 = Document.objects(_id="boe_585cb87956f09c48c999f90617e69038d3e8e0ceadca2b6030495d4126f4ab5d")
data.append(other_doc_1)

输出:

 [[Document boe_dd4a95f6ec1c41ba47239fe6fd688b8cc1232c3d25a68b76836172d99164cb82: date=2017-03-22 12:00:00, bank=Bank boe: name=Bank of England], [Document boe_585cb87956f09c48c999f90617e69038d3e8e0ceadca2b6030495d4126f4ab5d: date=2017-04-13 09:00:00, bank=Bank boe: name=Bank of England]]

期望的输出:

[Document boe_dd4a95f6ec1c41ba47239fe6fd688b8cc1232c3d25a68b76836172d99164cb82: date=2017-03-22 12:00:00, bank=Bank boe: name=Bank of England, Document boe_585cb87956f09c48c999f90617e69038d3e8e0ceadca2b6030495d4126f4ab5d: date=2017-04-13 09:00:00, bank=Bank boe: name=Bank of England]

所以我可以运行这个:

for i in other_doc:
doc = str(other_doc.extracted_text)
doc_tokens = tokenizer.tokenize(doc)
print(doc_tokens)

【问题讨论】:

    标签: python mongodb list iterable


    【解决方案1】:

    在 python 中,您可以简单地执行 data += other_doc 而不是调用 append。

    所以完整的代码是:

    data=[]
    other_doc = Document.objects(bank="boe_dd4a95f6ec1c41ba47239fe6fd688b8cc1232c3d25a68b76836172d99164cb82")
    data += other_doc
    other_doc_1 = Document.objects(_id="boe_585cb87956f09c48c999f90617e69038d3e8e0ceadca2b6030495d4126f4ab5d")
    data += other_doc_1
    

    【讨论】:

    • 谢谢,当 StackOverflow 允许我时,我会接受你的回答!
    【解决方案2】:

    您可以使用data += other_docdata.extend(other_doc)。 Extend 将一个列表添加到另一个现有列表的末尾。

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2017-11-17
      • 2016-03-09
      • 2021-11-13
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多