How can i print on new lines?

huangapple go评论63阅读模式
英文:

How can i print on new lines?

问题

如何在此函数中打印我的输出,使每个布尔值都在新的一行上。

def is_palindrome(n):
    return str(n) == str(n)[::-1]

numbers = list(map(int, input().split(', ')))
palindrome_status = [is_palindrome(n) for n in numbers]

for status in palindrome_status:
    print(status)

输出:

False
True
False
True
英文:

How can i print my output from this function and each boolean to be on new line.

def is_palindrome(n):
    return str(n) == str(n)[::-1]


numbers = list(map(int, input().split(', ')))
palindrome_status = [is_palindrome(n) for n in numbers]

print(palindrome_status)

Output:

[False, True, False, True]

Expecting:

False
True
False
True

答案1

得分: 1

最简单的方法是一个一个打印它:

[print(is_palindrome(n)) for n in numbers]


**但是**

不应该在具有副作用函数的情况下使用列表推导,为了使其更清晰,您应该使用普通循环:

for n in numbers:
print(is_palindrome(n))

英文:

The simplest would be print it one by one:

[print(is_palindrome(n)) for n in numbers]

BUT

List comprehesion shouldn't be used with side effect functions, to have it clean you should use normal loop:

for n in numbers:
    print(is_palindrome(n))

答案2

得分: 0

print("\n".join(map(str, palindrome_status)))
英文:

Convert boolean to string, then insert newlines.

print("\n".join(map(str, palindrome_status)))

答案3

得分: 0

  1. 使用for循环遍历元素,然后打印
for val in palindrome_status:
    print(val)
  1. 在解压缩列表时使用换行符作为打印分隔符
print(*palindrome_status, sep='\n')
英文:

There are two options:

  1. Use a for loop to iterate over the elements and then print

> for val in palindrome_status:
print(val)

  1. Use the print separator for newlines while unpacking the list

> print(*palindrome_status, sep='\n')

huangapple
  • 本文由 发表于 2023年2月6日 08:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定