Python: while循环超出条件

Python: While loop exceeded the condition

我编写了下面的代码来生成一个包含 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)

你的问题是这个循环,当你遍历 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 值是否为 <0.7 并且仅在它们为 <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