验证 python 中嵌套列表的输入
Validate input for nested list in python
这里 python 的新手。
我正在尝试验证用户输入是否为空以存储嵌套列表(x y 坐标)。如果用户没有输入任何内容,代码应该显示一条消息,例如"No input" 并会循环提示用户输入。
一直在到处搜索验证空嵌套列表或验证空输入,但我无法将这些知识放在一起。代码示例如下所示:
add = "y"
xy = []
#-------------------------------------
def count_list(l):
count = 0
for e in l:
if isinstance(e, list):
count = count + 1 + count_list(e)
return count
#--------------------------------------
while (add == "y"):
xy.append([(input("Input x value: ")), (input("Input y value: "))])
add = input("Additional (x, y)? [y/n] ")
qty = (count_list(xy))
print ("(x, y) coordinate(s) inserted:- " + str(xy))
print ("No. of coordinate(s) inserted:- " + str(qty))
输出
为此绞尽脑汁。注意第二个嵌套列表是空的。我试图找出如何停止代码继续,而是用消息 "no input" 提示用户。空嵌套列表的位置不要加入列表中
也不知道为什么我的 count_list 函数还包括在空嵌套列表中的计数。 T_T
当您看到输入为空时,您可以采取的措施是 continue
以避免计算空输入。
while (add == "y"):
x_val = input("Input x value: ")
y_val = input("Input y value: ")
# not x_val checks if the string is an empty string
if not x_val or not y_val:
print("Error: No input. Try again.")
continue
xy.append([(x_val), (y_val)])
add = input("Additional (x, y)? [y/n] ")
输出:
Input x value: 1
Input y value: 2
Additional (x, y)? [y/n] y
Input x value:
Input y value:
Error: No input. Try again.
Input x value: 5
Input y value: 6
Additional (x, y)? [y/n] n
(x, y) coordinate(s) inserted:- [['1', '2'], ['5', '6']]
No. of coordinate(s) inserted:- 2
这里 python 的新手。
我正在尝试验证用户输入是否为空以存储嵌套列表(x y 坐标)。如果用户没有输入任何内容,代码应该显示一条消息,例如"No input" 并会循环提示用户输入。
一直在到处搜索验证空嵌套列表或验证空输入,但我无法将这些知识放在一起。代码示例如下所示:
add = "y"
xy = []
#-------------------------------------
def count_list(l):
count = 0
for e in l:
if isinstance(e, list):
count = count + 1 + count_list(e)
return count
#--------------------------------------
while (add == "y"):
xy.append([(input("Input x value: ")), (input("Input y value: "))])
add = input("Additional (x, y)? [y/n] ")
qty = (count_list(xy))
print ("(x, y) coordinate(s) inserted:- " + str(xy))
print ("No. of coordinate(s) inserted:- " + str(qty))
输出
为此绞尽脑汁。注意第二个嵌套列表是空的。我试图找出如何停止代码继续,而是用消息 "no input" 提示用户。空嵌套列表的位置不要加入列表中
也不知道为什么我的 count_list 函数还包括在空嵌套列表中的计数。 T_T
当您看到输入为空时,您可以采取的措施是 continue
以避免计算空输入。
while (add == "y"):
x_val = input("Input x value: ")
y_val = input("Input y value: ")
# not x_val checks if the string is an empty string
if not x_val or not y_val:
print("Error: No input. Try again.")
continue
xy.append([(x_val), (y_val)])
add = input("Additional (x, y)? [y/n] ")
输出:
Input x value: 1
Input y value: 2
Additional (x, y)? [y/n] y
Input x value:
Input y value:
Error: No input. Try again.
Input x value: 5
Input y value: 6
Additional (x, y)? [y/n] n
(x, y) coordinate(s) inserted:- [['1', '2'], ['5', '6']]
No. of coordinate(s) inserted:- 2