如何在python中的列表中检查相同的字符串

如何检查列表是否在python中包含相同的字符串?我曾尝试在以前的堆栈交换问题中搜索类似的内容,但似乎找不到所需的示例。我目前正在编写一个基于条件频率分布的简单诗歌生成程序。有时,程序会重复返回一行包含几个单词的行。 例如:

“今天是冬天”和“今天我要遇见杜鹃”

如果发生这种情况,我想告诉我的计算机重新生成该行,直到制作出没有此问题的新行。我发现了摆脱同一行连续出现两次的单词的方法(例如“ the”),以及整行重复的问题(例如“ is is it it is”),但是由于某些原因,行会出现重复仍然可以。

这是我的代码,用于检查是否应重新生成一行。

                       for item in lineN:
                        if lineN.count(item) > 1: 
                            #Regens line if 2 words repeat infinitely. Ex: "it is it is it"
                            break
                        elif any(lineN[i]==lineN[i+1] for i in range(len(lineN)-1)): 
                            #Regens line if same word appears twice in a row. Ex: "the the"
                            break
                        else: 
                            #Poem is correct and will be returned from function
                            return lineN,strN
                            break

如何搜索列表中是否有相同的字符串?

lililili521 回答:如何在python中的列表中检查相同的字符串

基于注释,这是您的代码。

for item in lineN: 
    if len(lineN) != len(set(lineN)):
        break
    elif lineN.count(item) > 1: #Regens line if 2 words repeat infinitely. Ex: "it is it is it" 
        break 
    elif any(lineN[i]==lineN[i+1]:
        for i in range(len(lineN)-1)): #Regens line if same word appears twice in a row. Ex: "the the" 
             break 
    else: #Poem is correct and will be returned from function 
         return lineN,strN break

根据您的帖子,第一个条件应该足够。

本文链接:https://www.f2er.com/3135317.html

大家都在问