【问题标题】:Working through bugs of Python program, not sure why they are occuring解决 Python 程序的错误,不知道为什么会发生
【发布时间】:2020-08-29 02:30:13
【问题描述】:

我正在构建一个程序,以将具有特定长度的列表从字符串添加到更大的列表中。例如,在字符串“The quick brown fox jumped over the lazy dog”中,如果我将其拆分为 4 个列表,我的返回值将是

"[[The, quick, brown, fox], [jumped, over, the, lazy], [dog]]"

我的代码是:

text = "The quick brown fox jumped over the lazy dog"
micro = []
count = 1
split = text.split(" ")
total_list = []
for i in range(0, len(split)):
    print(split[i], count)
    if count < 5:
        micro.append(split[i])
        print(micro)
        if count == 4:
            total_list.append(micro)
            print(total_list)
            micro.clear()
            count = 0
     count+=1
print(total_list)

这样做的想法是将文本拆分为一个大列表,保留一个计数器以 4 个为一组添加,然后将较小的拆分添加到整个列表中。因为这个字符串很奇怪,所以我知道我不会将 dog 添加到末尾,鉴于我当前的设置,我不知道如何解决。我的输出是:1

['The']
quick 2
['The', 'quick']
brown 3
['The', 'quick', 'brown']
fox 4
['The', 'quick', 'brown', 'fox']
[['The', 'quick', 'brown', 'fox']]
jumped 1
['jumped']
over 2
['jumped', 'over']
the 3
['jumped', 'over', 'the']
lazy 4
['jumped', 'over', 'the', 'lazy']
[['jumped', 'over', 'the', 'lazy'], ['jumped', 'over', 'the', 'lazy']]
[[], []]

大多数情况下,我很困惑,想知道是否有更简单的方法可以做到这一点。我希望用它来分解以使用先验。由于我正在处理的数据规模(1100+ 组文本约 100 个字)我想分解,这就是为什么我想要一个列表列表。我希望整体上不那么密集。

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 我第一次看到标记为apriori的问题。
  • 这就是这个功能。我这样标记它是因为我希望将我从中获得的信息用于先验
  • Exploringgayfish 对此有所帮助!它现在的作用就像一个魅力

标签: python list apriori


【解决方案1】:

您可以为此使用range 和数组切片:

text = "The quick brown fox jumped over the lazy dog"
text = text.split()
result = []
step = 4
for i in range(0, len(text), step):
    result.append(text[i: i + step])
result
#[['The', 'quick', 'brown', 'fox'], ['jumped', 'over', 'the', 'lazy'], ['dog']]

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多