简体   繁体   English

如何将列表中的值与字符串进行比较?

[英]How to compare values in a list with a string?

I want to create a script which should prevent equal sentences.我想创建一个脚本来防止相等的句子。 Firstly, I thought that it was enough to just check if the previous and the current sentence are the same.首先,我认为只检查前一句和现在的句子是否相同就足够了。 But it turned out that no sentence should be duplicate.但事实证明,任何句子都不应该重复。 My first thought was to create a new list and save the created sentences in it.我的第一个想法是创建一个新列表并将创建的句子保存在其中。 After that, the program should check if the new sentence is on the list.之后,程序应检查新句子是否在列表中。 But it doesn't work at all and I don't know why.但它根本不起作用,我不知道为什么。 I hope you can help me.我希望你能帮助我。

*If you find any syntax mistakes it's because I translated the script to English and did a mistake. *如果您发现任何语法错误,那是因为我将脚本翻译成英文并且犯了一个错误。

import random

sentence = ''
previous_sentence = ''
sentence_list = []

def create_sentence():
    names = ["x","y", "z"]
    descriptions = ["a","b", "Dc"]
    global sentence
    global previous_sentence
    global sentence_list



    while sentence == previous_sentence:
        sentence_list.append(sentence)
        name = random.choice(names)
        description = random.choice(descriptions)
        sentence = f'{name} is a {description}'
        if sentence == previous_sentence and sentence in sentence_list:
            name = random.choice(names)
            description = random.choice(descriptions)
            sentence = f'{name} is a {description}'
        else:
            previous_sentence = sentence
            return sentence
    else:
        prevoius_sentence = sentence
        return sentence       

for i in range(50):
    print(create_sentence())

The script you've provided looks like it should prevent duplicate sentences from being generated, but there are a couple of issues with it that might be causing it not to work as intended.您提供的脚本看起来应该可以防止生成重复的句子,但它有几个问题可能导致它无法按预期工作。

First, in the while loop, you are adding the sentence to the sentence_list before checking if it's a duplicate.首先,在 while 循环中,您将句子添加到 sentence_list 中,然后再检查它是否重复。 So even if it's a duplicate, it will still be added to the list, which means that the check for duplicates later on will not work correctly.所以即使它是重复的,它仍然会被添加到列表中,这意味着以后的重复检查将无法正常工作。

Next, inside the while loop, you have an if-else block where you are re-assigning the sentence variable with a new sentence if the current sentence is a duplicate.接下来,在 while 循环内,您有一个 if-else 块,如果当前句子重复,您可以在其中用新句子重新分配句子变量。 However, this block should be inside the while loop so that it's executed every time a duplicate sentence is generated.但是,这个块应该在 while 循环内,以便在每次生成重复句子时执行它。

Additionally, you are using the same variable names for checking duplicate sentences and for the list of sentences, this can lead to confusion.此外,您使用相同的变量名称来检查重复的句子和句子列表,这可能会导致混淆。

Here's a revised version of your script that should work correctly:这是您的脚本的修订版本,应该可以正常工作:

import random

previous_sentence = ''
sentence_list = set()

def create_sentence():
    names = ["x","y", "z"]
    descriptions = ["a","b", "Dc"]
    global previous_sentence
    global sentence_list

    sentence = f'{random.choice(names)} is a {random.choice(descriptions)}'
    while sentence in sentence_list:
        sentence = f'{random.choice(names)} is a {random.choice(descriptions)}'
    sentence_list.add(sentence)
    previous_sentence = sentence
    return sentence

for i in range(50):
    print(create_sentence())

I rewrite your code in a bit cleaner way without global variables and to make this code more reusable:我在没有全局变量的情况下以更简洁的方式重写了您的代码,并使该代码更具可重用性:

import random

def create_sentence(names, descriptions, sentence_list):
    name = random.choice(names)
    description = random.choice(descriptions)
    sentence = f'{name} is a {description}'
    while sentence in sentence_list:
        name = random.choice(names)
        description = random.choice(descriptions)
        sentence = f'{name} is a {description}'
    sentence_list.append(sentence)
    return sentence

def main():
    names = ["x","y", "z"]
    descriptions = ["a","b", "Dc"]
    sentence_list = []

    for i in range(50):
        print(create_sentence(names, descriptions, sentence_list))

if __name__ == '__main__':
    main()


  • The create_sentence() function uses a while loop that continues generating new sentences until a sentence is generated that is not already in the sentence_list . create_sentence() function 使用while循环继续生成新句子,直到生成一个不在 sentence_list 中的sentence_list Once a unique sentence is generated, it is added to the sentence_list using the sentence_list.append(sentence) line.一旦生成了一个独特的句子,就会使用sentence_list.append(sentence)行将其添加到sentence_list中。
  • The function also makes sure that a new sentence is created until it is different from the previous sentence, by checking if the sentence is already in the list before it appends it to the list. function 还确保创建一个新句子,直到它与前一个句子不同,方法是在将句子附加到列表之前检查该句子是否已经在列表中。 This ensures that the list will only contain unique sentences.这确保列表将只包含独特的句子。
  • The function create_sentence() is separated from the main logic of the program, making it more reusable and easier to test. function create_sentence()脱离了程序的主要逻辑,复用性更好,测试更方便。
  • The function takes in the names , descriptions , and sentence_list as arguments, making it more clear what data the function depends on. function 将namesdescriptionssentence_list取为 arguments ,更清楚 function 依赖什么数据。
  • The function uses a while loop instead of global variables to keep track of previous sentence. function 使用while循环而不是全局变量来跟踪上一句。
  • The main function creates the variables and calls the create_sentence function in a for loop. main function 创建变量并在for循环中调用create_sentence function。
  • The main function is wrapped in a if name == 'main' block, it allows the code to be imported as a module without running the main function. main function 包裹在if name == 'main'块中,它允许代码作为模块导入而无需运行main function。
  • The variable and function names are in lower_case_with_underscores, making it more readable and consistent.变量和 function 名称采用 lower_case_with_underscores,使其更具可读性和一致性。
  • The code is more readable and easy to understand.代码更具可读性和易于理解。
  • The if else block is removed as it's not required. if else块被删除,因为它不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM