简体   繁体   English

如何从列表中查找和删除具有给定总字母数的字符串对

[英]How to find and remove pairs of strings with a given total letters count from a list

I've got a list, with each element being a word.我有一个列表,每个元素都是一个单词。 In this list, I want to find pairs of words whose added letter count is 20, print them and remove them from the list.在这个列表中,我想找到添加字母数为 20 的单词对,打印它们并将它们从列表中删除。

When there aren't any more words in the list matching the criteria, the program should stop.当列表中没有匹配条件的单词时,程序应该停止。

Here is the code I came up with, but as you will see, it has a lot of errors, with indexes going out of range and I can't figure out how to fix it, nor how to make the program to stop when there aren't any more words matching the criteria.这是我想出的代码,但正如您将看到的,它有很多错误,索引超出范围,我不知道如何修复它,也不知道如何让程序在那里停止不再有符合条件的词。

f = open('input.txt', 'r')

words = f.read().split()

c = 0
for word in words:
    c += 1

for i in range(c):
    letterCount = 0
    for letter in words[i]:
        letterCount += 1
    for j in range(i+1, c):
        letterCount2 = 0
        for letter in words[j]:
            letterCount2 += 1
        if letterCount + letterCount2 == 20:
            print(words[i], words[j])
            words.pop(i)
            words.pop(j)

Here is my suggestion.这是我的建议。 You must use len(list) or len(word) in order to get the length of a list of a word, it will make your life much easier.您必须使用 len(list) 或 len(word) 来获取单词列表的长度,这将使您的生活更轻松。 In the following code, we create a function that checks for such pairs of words and removes them.在下面的代码中,我们创建了一个 function 来检查此类单词对并删除它们。 We run this function until there is no other pair and the loop stops:我们运行这个 function 直到没有其他对并且循环停止:

f = open('input.txt', 'r')

words = f.read().split()

def find_pair(l):
    for i in range(len(l)-1):
        for k in range(i, len(l)):
            if len(l[i]+l[k])==20:
                return (i, k)
    return (0,0)

while True:
    x=find_pair(words)
    if x!=(0,0):
        words.pop(x[1])
        words.pop(x[0])
    else:
        break

print(words)

Use break;使用break; statement to exit from loop once you condition is satisfied满足条件后退出循环的语句

A simple solution without altering your word list:一个简单的解决方案,无需更改您的单词列表:

pairs=[]
for w1 in words:
    for w2 in words:
        if w1 in pairs or w2 in pairs:
            continue
        if w1 != w2 and len(w1) + len(w2) == 20:
            print(w1, w2)
            pairs.append(w1)
            pairs.append(w2)
            break

print(pairs)
print(list(filter(lambda x: x not in pairs, words)))

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

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