繁体   English   中英

在列表中搜索具有特定字符的字符串

[英]Search for strings in a list with specific characters

我想创建一段代码,在一个单词中输入一个字符和该字符的 position,然后该代码打印单词列表中包含该字母但不在 position 中的所有单词。

因此,例如,如果列表是 [arm, bark, smack, smog ] 我说字符是 A 并且首先代码将返回 bark 和 smack,而不是 arm,因为 A 首先是.

到目前为止我已经试过了

 wlist = ['arm','bark','smack','smog']
        letter13 = input('what was the letter: ')
        position13 = int(input('what was the position of the letter : '))
        filtered13 = [x for x in wlist if x != [position13 - 1] == letter13]
        print(filtered13)
bunch_of_words = ['arm', 'bark', 'smack', 'smog']
letter_index = 0
letter = 'a'

bunch_of_words = [word for word in bunch_of_words if letter in word and word[letter_index] != letter]

print(bunch_of_words)
def has_but_elsewhere(char, pos, wordlist):
    return [w for w in wordlist
            if len(w) >= pos and char in w and w[pos-1] != char]
>>> wordlist = ['arm', 'bark', 'smack', 'smog']
>>> print(has_but_elsewhere('a', 1, wordlist))
['bark', 'smack']

[x for x in wlist if x != [position13 - 1] == letter13]

您正朝着正确的方向前进,但在此代码中wlist是一个单词列表,因此x是一个类似"arm"的单词。 [position13 - 1]是一个包含数字的列表。 letter13是字母“a”。 所以这说:

'arm' 不等于(其中 1 等于字母 'a' 的列表)。

这对你的要求没有意义。 您需要x[]来索引单词并挑选出一个字母,并且您需要两个单独的测试(单词中的字母)和(不在特定位置的字母)。

例如

def test(letter, index):
    wordlist = ["arm", "bark", "smack", "smog"]

    return [w for w in wordlist if (letter in w) and (w[index] != letter)]


>>> print(test('a', 1))
['arm', 'smack']

暂无
暂无

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

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