我是 Python 新手,正在尝试编写代码来检查嵌套列表是否具有一组有效的数字。每一行和每一列都必须有效。我编写了一个名为 check_sequence 的函数来验证列表是否具有一组有效的数字。我如何从另一个函数调用该函数来检查该行是否有效?因此,例如,对于 check_rows,我需要这样的东西:
check_sequence(list):
checks if list is valid
check_rows(list):
For each of the rows in the nested list call check_sequence
这是我的 check_sequence 代码:
def check_sequence(mylist):
pos = 0
sequence_counter = 1
while pos < len(mylist):
print "The pos is: " + " " + str(pos)
print "The sequence_counter is:" + " " + str(sequence_counter)
for number in mylist:
print "The number is:" + " " + str(number)
if number == sequence_counter:
sequence_counter = sequence_counter + 1
pos = pos + 1
break
else:
# if list is at the last position on the last item
if sequence_counter not in mylist:
print "The pos is:" + " " + str(pos) + " and the last position is:" + " " + str(mylist[len(mylist) - 1])
print "False"
return False
print "True"
return True
所以我会像下面这样调用主要方法:
check_square([[1, 2, 3],
[2, 3, 1],
[3, 1, 2]])
def check_square(list):
if check_rows() and check_columns() == True:
return True
else:
return False
最佳答案
这是一个适用于任意二维列表的解决方案。
l = [[1,2,3],[1,2],[1,4,5,6,7]]
try:
if len([1 for x in reduce(lambda x, y :x + y, l) if type(x) != type(0)]) > 0:
raise Exception
catch Exception:
pass # error, do something
直觉是将列表展平,然后依次检查其类型是否为 int
。
关于python - 如何为嵌套列表中的每一行运行一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44423738/