我想看看在最后一次出现某个字符后两个字符串是否相互匹配。例如:
same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']
True
所以在这种情况下,我的某个角色是' - '。我想看看两个字符串的最后一个' - '之后的字符串是否相互匹配。 ' - '之后的字符串是'幻觉'。两个字符串。这是真的。
到目前为止,我有:
same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']
some_list = []
for string in same_list:
for ch in string:
if ch == '-':
new_string = string.split(ch)
some_list.append(new_string)
i = 0
for sublist[-1] in some_list:
我觉得我忘记了在python中执行此操作的更简单方法。我所能记住的只是while循环,但这将返回第一次出现' - ',而不是最后一次出现。此外,我写的函数返回第二个字符串两次,因为它被拆分两次。我该如何摆脱它?
答案 0 :(得分:0)
你可以做这样简单的事情(假设列表中的所有结尾都必须匹配):
def end_matches(*phrases): # phrases becomes a tuple that will take any number
phrase_endings = set() # number of positional parameters
for phrase in phrases:
end = phrase.split('-')[-1] # take the last element of the split list
phrase_endings.add(end)
return len(phrase_endings) == 1 # the set holds only unique values, so a set of
# length 1 means all values in the set are the same
您现在可以测试一下:
>>> same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']
>>> end_matches(*same_list) # unpack the list into individual positional arguments
True