如何在python中逐个字符地比较字符串与列表中的项目

时间:2018-07-14 10:48:18

标签: python string list

我有一个列表,我想将用户输入与此列表进行比较,但要逐个字符地比较。例如,用户只能输入某个字符,其余字符用点号保留。 (例如:V ... r..n) 如何比较每个字符的字符串,以及它是否仅包括用户输入的所有字符(跳过点)

list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()  # for example "V...r..n"
for i in list1:
    # if s include exactly characters in i (skip the dots)
        print(i)

4 个答案:

答案 0 :(得分:2)

您可以使用正则表达式:

import re

list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()  # for example "V...r..n"

re_s = re.compile(''.join('.' if ch == '.' else re.escape(ch) for ch in s) + '$')
for i in list1:
    if re_s.match(i):
        print(i)

编辑:其他答案中似乎缺少的另一个选项是使用itertools.zip_longest

from itertools import zip_longest

list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()  # for example "V...r..n"
for i in list1:
    if all(c1 == c2 for c1, c2 in zip_longest(i, s) if c2 != '.'):
        print(i)

答案 1 :(得分:1)

这是一种方式。有两个步骤。首先制作一个字典,将索引映射到相关字符。然后检查这些索引是否相等。

L = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]

s = input()
d = {k: v for k, v in enumerate(s) if v != '.'}

for item in L:
    if (len(s) == len(item)) and all(item[k] == v for k, v in d.items()):
        print(item)

# V...r..n
# Vaporeon

答案 2 :(得分:0)

使用正则表达式,使用jpp的解决方案或使用以下一种方法可以解决该问题:

list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()  # for example "V...r..n"
for word in list1:
    l = len(word)
    c = 0
    flag = True
    while c < l and flag:
        if s[c] != '.':
            if s[c] != word[c]:
                flag = False
        c += 1
    if flag:
        print(word)

答案 3 :(得分:-1)

这里有一些很难解决的解决方案。我发现这是最简单且可行的解决方案。

list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()  # for example "V...r..n"
matchedList = []
for i in list1:
    inputInList = True
    for letter in s:
        if not letter in i:
            inputInList = False
            break
    if inputInList:
        matchedList.append(i)

print(matchedList)