You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

输入列表元素出错时,如何避免重新输入全部元素

解决列表元素非空且不重复的输入问题

你当前的代码存在几个问题:

  • 空元素仅做了一次重新输入,如果再次输入空值仍会被加入列表
  • 重复元素仅打印提示,没有移除重复项也未要求重新输入
  • 内外层循环使用了相同的变量i,会导致逻辑混乱

以下是修正后的代码,实现输入空值/重复值时仅重新输入当前出错元素的需求:

first = []  

n = int(input("Enter the number of elements of the first list (elements are not duplicated!): ")) 
for _ in range(n):
    while True:
        element = input("Enter element of the list: ")
        # 检查空元素
        if element == "":
            print("Empty element is not allowed, try again")
            continue
        # 检查重复元素
        if element in first:
            print("Duplicated element is not allowed, try again")
            continue
        # 符合要求则跳出循环
        break
    first.append(element)

print(first)

代码说明:

  • 在外层循环的每一轮中,用while True持续获取输入,直到得到符合要求的元素
  • 先判断是否为空,为空则提示并继续循环重新输入
  • 再判断元素是否已在列表中,重复则提示并继续循环
  • 当输入符合要求时,跳出while循环,将元素加入列表

这样就能保证每一个加入列表的元素都是非空且唯一的,且出错时仅需重新输入当前元素,无需从头开始。

内容的提问来源于stack exchange,提问作者gleb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:51:08