【问题标题】:get pair-elements from nested lists of increasing size从增加大小的嵌套列表中获取对元素
【发布时间】:2019-05-06 00:42:10
【问题描述】:

这可能是我正在尝试使用不符合我需要的数据结构,但是......鉴于此:

import itertools

listOfFileData = [['[', 'Emma', 'by', 'Jane', 'Austen'] ,['[', 'Persuasion', 'by', 'Jane', 'Austen'] ,['[', 'Sense', 'and', 'Sensibility', 'by'] ,
['[', 'The', 'King', 'James', 'Bible'] ,['[', 'Poems', 'by', 'William', 'Blake'] ,['[', 'Stories', 'to', 'Tell', 'to'] ,
['[', 'The', 'Adventures', 'of', 'Buster'] ,['[', 'Alice', "'", 's', 'Adventures'] ,
['[', 'The', 'Ball', 'and', 'The'] ,['[', 'The', 'Wisdom', 'of', 'Father'] ,['[', 'The', 'Man', 'Who', 'Was'] ,
['[', 'The', 'Parent', "'", 's'] ,['[', 'Moby', 'Dick', 'by', 'Herman'] ,['[', 'Paradise', 'Lost', 'by', 'John'] ,
['[', 'The', 'Tragedie', 'of', 'Julius'] ,['[', 'The', 'Tragedie', 'of', 'Hamlet'] ,['[', 'The', 'Tragedie', 'of', 'Macbeth'] ,
['[', 'Leaves', 'of', 'Grass', 'by'] ]

#print(len(listOfFileData)) # should show 18 files, each is a list of tokens. 

filesDataPairsList = list(itertools.combinations(listOfFileData, 2)) # requires itertools library file(s)

filesDataPairsListTesting = []
for i in range(2,19,2): # 2,4,6,8,...18
    combinationOfPairsList = list(itertools.combinations(listOfFileData[:i], 2)) # make a list, of increasingly sized pairs
    filesDataPairsListTesting.append(combinationOfPairsList)

#print(len(filesDataPairsListTesting)) # should have 9 lists
#print(len(filesDataPairsListTesting[8])) # should have 153 pairs

如何在一个循环中找到每一对?我一直在解决以下问题。但我没有到达那里。

for permutations in filesDataPairsListTesting:
#     print(len(permutations)) # if uncommented should read, 1,6,15,28....153
    for numOfPairs in range(len(permutations)):
        for pair in permutations:
            permutations[0]
            permutations[1]

我想访问每个列表对 [[],[]],以便能够处理 for 块中每对列表中的每个文档。

所以在我的 filesDataPairsListTesting 列表中使用元素 0。我可以很容易地找到每个项目,因为

        permutations[0]
        permutations[1]

但是第二个元素有 6 对...?所以我必须遍历元素 1 6 次,(怎么做?)这样我才能得到 permutations[0],permutations[1]。正是这部分让我感到震惊。

【问题讨论】:

  • 欢迎堆栈溢出。如果您希望我们提供帮助,请创建一个最小、完整且可验证的示例 (stackoverflow.com/help/mcve)。就像现在一样,我无法运行您的代码,而且很难弄清楚它应该做什么
  • 道歉。我以为我有。编辑以改进代码格式并引入任何 requ 库。
  • 整个第一块代码与您的问题无关。只是给我们filesDataPairsListTesting 带有虚拟值。没有人会安装nltk 包,只是为了让他们可以运行您的示例!即使他们会 - 同样,第一部分不相关,只需将其删除
  • 啊,现在我明白你的意思了。我删除了库并创建了所需数据集的示例,而不是包含 nltk 库。我错误地认为其他人可能已经在使用那个了。

标签: python list nested nlp corpus


【解决方案1】:

您基本上只有嵌套列表。只需遍历两者。例如:

ls = [
    [
        ([1, 2, 3], ["a", "b", "c"]),
        ([1, 2, 3], ["d", "e", "f"])
    ],
    [
        ([4, 5, 6], ["a", "b", "c"]),
        ([4, 5, 6], ["d", "e", "f"]),
        ([4, 5, 6], ["g", "h", "i"])
    ]
]

for pairs in ls:
    for pair in pairs:
        print(pair)

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2011-02-13
    • 2023-02-04
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多