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

2024-03-29 10:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

“冬天是它”“今天下雨是它”和“遇见布谷鸟的时候我想我”

如果出现这种情况,我想告诉我的计算机重新生成该行,直到生成一条没有此问题的新行。我已经找到了一些方法来消除同一个单词在一行中出现两次(比如“the”),以及整行重复出现的问题(比如“is it it is it is is it is 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

如果列表中有相同的字符串,如何搜索?你知道吗


Tags: the字符串in程序列表forifis
1条回答
网友
1楼 · 发布于 2024-03-29 10:25:36

根据评论,这是你的代码。你知道吗

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

根据你的职位,第一个条件应该足够。你知道吗

相关问题 更多 >