Python 调试:如何显示“无”的序列
我失去了打印的能力Python 调试:如何显示“无”的序列,python,python-3.x,Python,Python 3.x,我失去了打印的能力 "The median cannot be found" 基于序列中没有任何内容。这是我当前使用的代码,没有,这不起作用 def print_median(seq): if print_median(sep) = None: print("The median cannot be found.") else: median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2
"The median cannot be found"
基于序列中没有任何内容。这是我当前使用的代码,没有,这不起作用
def print_median(seq):
if print_median(sep) = None:
print("The median cannot be found.")
else:
median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2
print("The median of " + str(seq) + " is " + str(median) + ".")
还尝试了使用((),)和一些随机尝试,但也没有成功。
预期的结果是
>>> print_median(())
The median cannot be found.
以及生产
>>> print_median((-12, 0, 3, 9))
The median of (-12, 0, 3, 9) is 1.5.
因为当按照惯例有数字输入到seq.时,Python序列是错误的当且仅当它们为空时
if seq:
...
else:
print("The median cannot be found.")
如果将函数限制为,则只需测试序列是否为False,因为在Python中空容器是
False
:
def print_median(seq):
if not seq:
print("The median cannot be found.")
else:
median = (seq[len(seq) // 2 - 1] + seq[len(seq) // 2]) / 2
print("The median of " + str(seq) + " is " + str(median) + ".")
在Python3中,只处理序列,在类似于print_median(范围(10))
的情况下会失败
鉴于您正在为Python 3编写许多项,我将重写您的函数,以使用try
和except
,并通过调用传递序列上的list
来处理生成器:
def print_median(seq):
items=list(seq)
try:
median = (items[len(items) // 2 - 1] + items[len(items) // 2]) / 2
print("The median of {} is {}.".format(items, median))
except IndexError:
print("The median cannot be found.")
现在将按照您的预期处理生成器、列表和空序列:
>>> print_median([1,2,3])
The median of [1, 2, 3] is 1.5.
>>> print_median(e for e in [1,2,3])
The median of [1, 2, 3] is 1.5.
>>> print_median(range(10))
The median of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is 4.5.
>>> print_median([])
The median cannot be found.
你的意思是如果没有向函数传递任何内容,或者传递的是一个空序列吗?只需执行
如果没有seq:print(“无法找到中间值”)
什么是“不起作用”的意思?如果print\u median(sep)=None你的行似乎有两个问题:sep
没有定义,但即使定义了,不能在if
语句中使用变量赋值。相反,使用==
表示相等,或者如果你想表现得更出色,则使用为None
。问题是生成器将始终为True
,但可能为空…OP不会传递生成器,因为他在非空情况下使用[]
访问和len()
。