【问题标题】:I want this python problem's output in a perticular format, but dont know how to format it?我希望这个 python 问题以特定格式输出,但不知道如何格式化?
【发布时间】:2020-07-12 09:37:03
【问题描述】:

这是我的程序:

def question_second_solution(nums):
    print("Even Numbers: ")
    even_nums = list(filter(lambda x: x%2==0,nums))
    print(even_nums)
    print("Odd Numbers: ")
    odd_nums = list(filter(lambda x: x%2!=0,nums))
    print(odd_nums)
    return nums

question_second_solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

那么我怎样才能得到以下给定格式的输出: 偶数:[2, 4, 6, 8, 10],奇数:[1, 3, 5, 7, 9]

【问题讨论】:

  • 这能回答你的问题吗? String formatting in Python 3
  • print 函数在你的字符串后面隐式地输出一个换行符,但是你可以用 end 参数将这个换行符更改为任何其他字符。因此,如果您在字符串结束后不需要任何内容​​,请执行以下操作:print("Some text", end="")。不过,我会推荐 Tom Ron 的 f-string 解决方案。
  • 这能回答你的问题吗? How to print without newline or space?

标签: python lambda


【解决方案1】:
print(f"Even numbers: {even_nums}, Odd numbers: {odd_nums}")

【讨论】:

    【解决方案2】:

    如果您只想将输出作为字符串返回,请使用以下函数。这里even_nums和odd_nums排列成一个字符串并返回值。

    def question_second_solution(nums):
        even_nums = list(filter(lambda x: x%2==0,nums))
        odd_nums = list(filter(lambda x: x%2!=0,nums))
        return "Even Numbers: {} Odd numbers: {}".format(even_nums, odd_nums)
    

    如果您想将 even_nums 和 odd_nums 值作为列表返回并重复使用这些值进行进一步处理,那么您可以将这些值作为列表的元组返回。如下:

    return (even_nums, odd_nums)
    

    第二个用例示例:

    evens, odds = question_second_solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    
    print("Even numbers are: ", evens)
    print("Odd numbers are: ", odds)
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      你只能用一行来完成。

      def question_second_solution(nums):
          print(f"Even Numbers: %s, Odd numbers %s" % ([x for x in nums if x%2 == 0], [x for x in nums if x%2 != 0]))
      

      字符串中包含 %s 的字符串格式,并在字符串后注入带有 % 的值。

      【讨论】:

      猜你喜欢
      • 2020-07-12
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多