如何在Python中逐字比较字符串与列表中的项

2024-09-29 23:28:01 发布

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

我有一个列表,我想比较用户输入与该列表,但字符字符。例如,用户只能输入一些字符,其余的字符用点隔开。(例如: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)

Tags: 字符串用户in列表for字符list1flareon
3条回答

可以使用正则表达式:

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)

有几种方法可以解决它,用regex,用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)

这里有一条路。有两个步骤。首先将索引映射到相关字符。然后检查这些索引是否相等。你知道吗

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

相关问题 更多 >

    热门问题