英文:
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
- 使用for循环遍历元素,然后打印
for val in palindrome_status:
print(val)
- 在解压缩列表时使用换行符作为打印分隔符
print(*palindrome_status, sep='\n')
英文:
There are two options:
- Use a for loop to iterate over the elements and then print
> for val in palindrome_status:
print(val)
- Use the print separator for newlines while unpacking the list
> print(*palindrome_status, sep='\n')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论