【发布时间】:2015-11-13 00:38:03
【问题描述】:
我正在学习python并尝试了字谜生成器练习,然后决定尝试不同的生成字谜的方法,然后决定生成子字谜。我遇到的问题是需要比较列表,然后需要从 list_1 中删除 list_2 以说明它是否是子字谜,但是这没有发生,当我运行它时,第一个字母被删除,然后一个字母两个词都是一样的。我的代码如下:
def sub_anagram(word_1, word_2):
#letters need to be sorted into alphabetical order
list_1 = [c for c in word_1] #turns the string into a list
#list_1.sort() #sorts the list alphabetically
print(list_1)
list_2 = [c for c in word_2] #turns the string into a list
#list_2.sort() #sorts the list alphabetically
print(list_2)
#then the lists get compared
#loop to check if any letters from list_2 are in list_1
for list_2 in list_1:
#removes the letters in list_1 that are in
list_1.remove(list_2) list_2
print(list_2)
print(list_1)
list_1[len(list_1)-1] #checks the length of the list
if list_2 == list_1:
print("It is a sub-anagram")#return true if it is a sub-anagram
else:
print("It is not a sub-anagram") #return false if not
print("Sub-Anagram Antics")
#user inputs two words
#user input word 1
word_1 = input("Enter a word: ")
#user input word 2
word_2 = input("Enter a word: ")
#call function
sub_anagram(word_1, word_2)
【问题讨论】:
-
你能举几个例子吗?
-
您的缩进不正确。在 list_1 中的 for list_2 之后,至少要缩进一行。当您说“list_2 需要从 list_1 中删除”时,您的意思是 list_2 中的项目应该从 list_1 中删除,还是 list_2 应该是 list_1 中的一个元素?提供输入和预期输出的示例将有助于我们为您提供帮助。
-
您的问题不包含问题。您的代码对我来说就像一个完整的代码(即使我没有尝试过)。那么,您是在寻求帮助以查找错误,还是有真正的概念性问题?
-
作为一般提示,您应该尝试使用更有意义的名称,因为这可以提高可读性并帮助我们理解您的代码,并帮助您了解代码的功能。例如,列表不必命名为列表,而是可以用它包含的内容命名:例如
words。列表中的项目(例如在您的 for 循环中)不应称为列表,因为这会分散名称所代表的内容。而是在遍历任意对象时调用它item,或者当你有一个单词列表时调用它words。 -
@Jane:
printing 你不会回来的。
标签: python python-3.x