【问题标题】:Python: While loop exceeded the conditionPython:While循环超出了条件
【发布时间】:2021-04-09 06:52:40
【问题描述】:

我编写了下面的代码来生成一个包含 25 个列表的列表,其中每个列表有 40 个元素。但是,主要问题是所有列表的排序元素之间的相似性较低(我尝试从 difflib 应用 SequenceMatcher)。虽然条件是在内部列表数 = 25 时停止循环,但我得到了 32 个内部列表。

这是我的代码:

import random
from difflib import SequenceMatcher


def string_converter(input_list):
    string = ""
    for m in input_list:
        string += str(m)
    return string


lists = []
strings = []
e = 0

while e <= 25:
    list_one = []
    n = 0
    for i in range(40):
        if 7 < n < 33:
            i = random.randint(0, 3)
            list_one.append(i)
            n += 1
        else:
            i = random.randint(0, 2)
            list_one.append(i)
            n += 1
    list_string = string_converter(list_one)
    if e == 0:
        strings.append(list_string)
        lists.append(list_one)
        e = 1
    else:
        for s in strings:
            if SequenceMatcher(None, list_string, s).ratio() < 0.7:
                strings.append(list_string)
                lists.append(list_one)
                e += 1

print(e)
print(lists)
print(len(lists))
print(strings)

【问题讨论】:

  • 也许你想用while len(lists) &lt;= 25而不是while e &lt;= 25

标签: python arraylist while-loop conditional-statements difflib


【解决方案1】:

你的问题是这个循环,当你迭代strings时,它可以将list_one的多个副本附加到lists

for s in strings:
    if SequenceMatcher(None, list_string, s).ratio() < 0.7:
        strings.append(list_string)
        lists.append(list_one)
        e += 1

您需要做的是检查 所有 SequenceMatcher 值是否为 &lt;0.7 并且仅在它们是时附加。像这样的:

if all(SequenceMatcher(None, list_string, s).ratio() < 0.7 for s in strings):
    strings.append(list_string)
    lists.append(list_one)
    e += 1

【讨论】:

  • 它给了我一个错误,告诉我:。 if all(SequenceMatcher(None, list_string, s).ratio()
  • @KarimYosefRezk 您需要包含迭代器部分:all(SequenceMatcher(None, list_string, s).ratio() &lt; 0.7 for s in strings)
  • 最后一个问题:它返回的是 26 而不是 25,你能告诉我解释吗?
  • @KarimYosefRezk 这是因为你有 e &lt;= 25 所以 e 计数 0, 1, 2, ..., 25 这是 26 个值。只需将该测试更改为e &lt; 25
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 2018-03-11
  • 2012-03-01
相关资源
最近更新 更多