【问题标题】:Return and print giving different outputs in Python返回并打印在 Python 中给出不同的输出
【发布时间】:2020-01-23 01:56:11
【问题描述】:

我正在尝试合并两个数组并返回排序后的数组(leetcode 上的#88),这是我使用的代码:

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        if (m > 0 and n > 0):
            merged = nums1[0:m] + nums2[0:n]
            result = sorted(merged)
            print(result)
            return result

输入是

[1,2,3,0,0,0,0]
3
[2,5,6]
3

输出是这样的 -

谁能解释一下为什么 print 和 return 给出不同的输出?

【问题讨论】:

  • 您在哪里运行该代码?在本地运行时,我得到[1, 2, 2, 3, 5, 6] 作为标准输出和结果。
  • 另外,你为什么要在输出中看到0
  • List 是自定义类吗?因为如果我要尝试使用您的代码:NameError: name 'List' is not defined
  • @HubertGrzeskowiak 我的猜测是问题期望合并和排序在第一个列表中完成?

标签: python arrays python-3.x sorting return


【解决方案1】:

转到question并选择python3作为语言,我们会看到以下存根:

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

注意注释 - 测试框架正在查看 nums1 的状态,而不是您返回的值 - 实际上,规范是不返回任何内容。

您正在打印返回变量,这实际上就是您返回的内容。但是这个问题实际使用的变量并不是这个函数的返回值。

阅读规范,无论以何种格式呈现,在编写任何内容之前始终是一个很好的第一步。

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    相关资源
    最近更新 更多