现在我的所有代码都是在我的所有单词中找到所有a
。我想要它做的就是找到以我输入的字母开头的单词来找到单词。例如。 A
会找到activity
,again
和ago
字样。我试着寻找每一个地方,找不到我需要的答案。
dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':
choice = input("?")
if choice == 'a':
for a in dictionary:
newlist.append(choice.lower())
print(newlist)
答案 0 :(得分:1)
dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':
choice = input("?")
if choice == 'a':
for item in dictionary:
if(item[0] == choice):
newlist.append(item)
print(newlist)
您的上述代码未检查字典中每个项目的第一个字符。它只是遍历字典中的每个项目,并将“选择”(在本例中为“a”)附加到“newList”,然后在“newList”中打印当前项目
要解决此问题,您需要根据您的选择检查字典中每个项目的第一个字母,然后只将这些特定项目附加到“newList”
答案 1 :(得分:1)
Python字符串实际上有一个startswith
方法:)在您的情况下,它等同于string[0]
。
dictionary=["activity","again","ago","begin","behaviour","beyond","camp","cannon","cell","discussion","doctor","display","else","estimate","establish","fudge","flight","fight","gear","great","grunt","how","hoe","house","impact","image","implication","just","job","judge","keep","key","kai"]
newlist=[]
choice = ''
while choice != 'q':
choice = input("?")
for a in dictionary:
if a.startswith(choice.lower()):
newlist.append(a)
print(newlist)
答案 2 :(得分:0)
任何人都需要代码并运行代码打印一段时间。这应该有助于:
count = 0
while count < len(newlist):
count = count + 1
print(newlist)
length = len(newlist)