我在jupyter笔记本中没有获得以下代码的输出。 此代码基本上检查单词的平均长度并将其打印出来。 我发现在将每个单词附加到“新”(列表)之后,while循环甚至无法正常工作。
我知道还有其他方法可以以更简单的方式执行此操作,但是我希望它可以正常工作。
st = 'Print every word in this sentence that has an even number of letters'
new=[]
i=0
for words in st.split():
new.append(words)
l=len(st)
while i<=l:
if len(new[i])%2==0:
print(new[i])
i=i+1
答案 0 :(得分:3)
有几个问题。例如,l = len(st)
应该是l = len(new)
,i <= l
应该是i < l
,并且i=i+1
应该被分隔。
另一方面,更好的方法是
st = "Print every word in this sentence that has an even number of letters"
for word in st.split():
if len(word) % 2 == 0:
print(word)
答案 1 :(得分:0)
我不知道如何解决您的代码,因为它有太多错误。刚刚写了最接近可能的解决方案
docker pull
答案 2 :(得分:0)
问题是i=i+1
发生在if
语句中。这意味着我从不超过0,因为第一个单词的长度是奇数。要解决此问题,请将i = i + 1放在if
语句之外。
while i<=l:
if len(new[i])%2==0:
print(new[i])
i=i+1
答案 3 :(得分:0)
由于第一个条件不满足并且i不会增加,因此您会收到无限循环。
答案 4 :(得分:0)
st = 'Print every word in this sentence that has an even number of letters'
new=[] # You can create the list of words here instead of a loop
i=0
for words in st.split():
new.append(words)
l=len(st) # len(new)
while i<=l: # i < l (since indexing of i starts from 0 to n-1 length
if len(new[i])%2==0:
print(new[i])
i=i+1 # this needs to be outside loop, since it will only increment if even word is found
st = 'Print every word in this sentence that has an even number of letters'
new = s st.split()
i = 0
l = len(new)
while i < l:
if len(new[i])%2 == 0:
print (new[i])
#else:
# pass
i = i+1
答案 5 :(得分:0)
st = "Print every word in this sentence that has an even number of letters"
new=[]
i=0
for words in st.split():
new.append(words)
l=len(words)
while i<l:
if len(new[i])%2==0:
print(new[i])
i=i+1
此外,您可以使用以下命令执行相同的任务:
st="Print every word in this sentence that has an even number of letters"
[word for word in st.split() if len(word)%2==0]