我试图使用列表理解来循环字母在一个词,并得到新的组合后,删除一个字母在一次。
例如,输入字符串是一个单词:“bathe”
我想把输出列在一个列表中(最好是),下面是a,bthe,bahe,bate
呃,从左到右只经过一次
单词=“洗澡”
newlist1 = [word1::,(word 1:2+ word-3:),(word:2 + word-2:),word:3 + word-1:]
打印(“样本1”,newlist1)
newlist2 =[(word 1:2+ word-3:),(word 1:2+ word-3:),(word:2 + word-2:),word:3 + word-1:]
打印(“样本2”,newlist2)
我第一次通过这个代码,但现在被卡住了。
X= [(word:i + word-j:) i in range(1,4) for j in range(4,1,-1)]
我得到的输出显然不正确,但(希望)有方向(当涉及到使用列表理解时)。
‘洗澡’,'bthe','bhe','baathe','bahe',‘bahe’,'batathe','batthe',‘bahe’
发布于 2022-09-16 04:04:51
你可以这样做:
首先,需要某种方法从列表中删除某个元素:
def without(lst: list, items: list) -> list:
"""
Returns a list without anything in the items list
"""
new_lst = lst.copy()
for e in lst:
if e in items:
items.remove(e)
new_lst.remove(e)
return new_lst然后,使用该函数,您可以创建新单词列表。
new_word_list = ["".join(without(list(word), list(letter))) for letter in word]正如您想要的输出中所显示的,您不需要这个结果的最后一个结果,所以只需添加:-1。
new_word_list = ["".join(without(list(word), list(letter))) for letter in word][:-1]另一种方法是(不使用without函数):
new_word_list = [word[:index - 1] + word[index:] for index, _ in enumerate(word)][1:]最后的[1:]是因为在开头有一个奇怪的字符串(因为它的编写方式)。奇怪的字符串是bathbathe (当word是bathe时)
https://stackoverflow.com/questions/73739628
复制相似问题