首页 > 解决方案 > 我需要重新打印我的输入,但只打印我的哨兵

问题描述

sentinel = "Done"
input_string(str(input("Enter strings (end with DONE):")))

while input_string != sentinel:
    input_string= str(input())
    
#remove duplicates   
res = []
for i in input_string:
    if i not in res:
        res.append(i)

print("\nUnique list:")
print(input_string)

这是预期的输出

Sample I/O
Enter strings (end with DONE):
the
old
man
and
the
sea
DONE
Unique list:
the
old
man
and sea

标签: python

解决方案


在您的代码中,input_string不是列表,而是每个输入重新分配的值。正因为如此,1)for循环并没有完全按照您的意图执行,2)print(input_string)只是打印最后一个用户输入,即“完成”。

以下应该做的工作:

sentinel = "DONE"
input_list = []
input_string = str(input("Enter strings (end with DONE):"))
input_list.append(input_string)

while input_string != sentinel:
    input_string = str(input())
    input_list.append(input_string)

#remove duplicates   
res = []
for i in input_list:
    if i not in res and i != "DONE":
        res.append(i)

print("\nUnique list:")
print(res)

PS:在我的片段中,我已更改为“ DONE sentinel”以确保.sentinelinput_string


推荐阅读