(这是Python 3)
我试图写一个简单的函数来返回一个数字列表的平均值。我使用for
循环在打印出平均值之前打印出列表中的值。我在设置列表中倒数第二个值以不同于其他值的方式打印时遇到问题。我希望所有列表值之间有一个逗号,直到倒数第二个值为止,我只想在最后一个值后面加一个句号。在
如果我把我的列表定义为
list1 = [1, 3, 5, 7]
然后我想返回一个字符串:
^{pr2}$不幸的是,我得到的是:
"The values contained in the list are as follows: 1, 3, 5, and 7."
换句话说,我无法区分从第二到最后的列表值(我无法删除5后面的逗号);尽管我能够区分列表中的最后一个值(即7)。在
为了将列表中的倒数和倒数第二个值分开(即5和7),我将它们定义为变量:
finalElem2 = nlist[-1]
penultElem = nlist[-2]
然后我使用for
和and
语句排除这两个值。到目前为止,我得到的代码是:
def average1(nlist):
length = len(nlist)
finalElem2 = nlist[-1]
penultElem = nlist[-2]
sum_1 = 0
print("The values contained in the list are as follows: ",end="")
for i in nlist:
if i != finalElem2 and penultElem:
print(i, end=", ")
if i == finalElem2:
print("and ",i,".",sep="")
print("The length of the list is",length,"values.")
for i in nlist:
sum_1 = sum_1 + int(i)
average2 = sum_1 / length
print("The average is",average2)
就像我前面提到的,调用average1(list1)返回"The values contained in the list are as follows: 1, 3, 5, and 7."
我本以为下面的两行意味着列表值5(即penultElem,即倒数第二的列表值)不会在末尾用逗号打印,但事实并非如此。在
if i != finalElem2 and penultElem:
print(i, end=", ")
这是我想我应该补充的,如果不是印刷的话。。。它将打印“5”,后面不带逗号。在
if i == penultElem:
print(i)
我是不是错过了一些很明显的东西?抱歉,如果我是,我对这个很陌生。谢谢你的帮助!在
我建议这样做:
这里的主要改进是使用单个
if/elif/else
块来更有效地过滤所需的结果。如果您考虑列表中数字后面的字符:一些字符以,
结尾,一个以and
结尾,另一个以.
结尾,那么这是使用单个if/else
块来处理这些情况的一个很好的理由。在您还可以使用
^{pr2}$pop()
从列表末尾返回两次元素:有一个更简单的方法。你可以在适当的地方“unpack”你的列表。这个遗嘱工作:-
不过,如果你的列表中有不同数量的元素,那就不太好了。我只是想让你看看这个方法。 在
经过进一步调查,我认为这是一个很好的方法你:-在
^{pr2}$从而产生所需的输出。在
只要你至少有两个元素,这就可以工作。在
如果i==penultElem,则此语句不能应用于,因为这将导致后面的逗号:
将该部分更新为:
^{pr2}$以下是完整的更新代码:
打印:
相关问题 更多 >
编程相关推荐