比较python中多个字符串的第N个字母和第N个字符



我不太明白这一点。

我有多个五个字母长的字符串,我想将字符串的每个字母与单个字符串进行比较,然后知道字符串的第N个字母中是否有任何一个等于我将其与之进行比较的字符串的第n个字母,如下所示:

string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
the_word = 'shine'
if the_word[0] == string_1[0] or the_word[0] == string_2[0] or the_word[0] == string_3[0] or the_word[1] == string_1[1] or the_word[1] == string_2[1]... and so on...
print('The Nth letter of some of the strings is equal to the Nth letter of the_word')
else:
print('None of the letters positions correspond')

如果有多个字符串,我想比较If语句会变得很长,所以必须有更好的方法。

我还想知道对应的字母是什么(在这种情况下,它们将是H(字符串_1[1]==单词[1](、I(字符串_3[2]==单词[2](和N(字符串_3[3]==单词[3](

如果有多个对应的字母,我希望返回包含所有字母的列表。

此外,我不需要知道对应的字母是否是第一个,也不需要知道字母在单词中的位置,只需要知道是否有(以及什么(对应的字母。

我觉得这种解释很难,所以很抱歉可能会混淆,很乐意详细说明。

谢谢!

IIUC,您可以使用zip-获得您想要的内容

base_strings = zip(string_1, string_2, string_3)
for cmp_pair in zip(the_word, base_strings):
if (cmp_pair[0] in cmp_pair[1]):
print(cmp_pair[0])

输出

h
i
n

您可以将逻辑提取到一个专用函数,并在要检查的字符串的每个字符上调用它:

string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
the_word = 'shine'
def check_letter(l, i, words):
match = []
for w in words:
if w[i] == l:
match.append(w)
return match
for i in range(len(the_word)):
l = the_word[i]
print("checking letter: {}".format(l))
match = check_letter(l, i, [string_1, string_2, string_3])
if (len(match) > 0):
print("found in: {}".format(match))
else:
print("found in: -")

以上代码导致:

$ python3 test.py
checking letter: s
found in: -
checking letter: h
found in: ['ghost']
checking letter: i
found in: ['blind']
checking letter: n
found in: ['blind']
checking letter: e
found in: -

也许这可以回答您的问题:

strings = ['ghost', 'media', 'blind']
the_word = 'shine'
for s in strings:
check = []
lett = []
for i in range(len(s)):
if s[i] == the_word[i]:
check.append(i)
lett.append(s[i])
if check:
print('The letters {0} (position {1}) of the string {2} match to 
the word {3}'.format(lett,check,s,the_word))
else:
print('No match between {0} and {1}'.format(s,the_word))

一个直接的方法是:

string_1 = 'ghost'
string_2 = 'media'
string_3 = 'blind'
string_4 = 'trenn'
the_word = 'shine'
string_list = [string_1, string_2, string_3]
duplicate_letters_list = []
for string in string_list:
for i in range(5):
if the_word[i] == string[i]:
print(f'{i}th letter is in {string} is a duplicate')
if the_word[i] not in duplicate_letters_list:
duplicate_letters_list.append(the_word[i])
print(duplicate_letters_list)

输出

1th letter is in ghost is a duplicate
2th letter is in blind is a duplicate
3th letter is in blind is a duplicate
['h', 'i', 'n']

相关内容

  • 没有找到相关文章

最新更新