[英]Build pyramid pattern using list comprehension in python?
Can anyone show me how to create half pyramid using list comprehension ?谁能告诉我如何使用列表理解创建半金字塔?
For example例如
*
**
***
I tried but did not succeed.我尝试过但没有成功。
I am trying to convert following code into using dictionary comprehension我正在尝试将以下代码转换为使用字典理解
for i in range(0, n):
for j in range(0, i+1):
print("* ",end="")
print("\r")
Do not use list-comprehensions for side-effect (eg like printing).不要将列表理解用于副作用(例如打印)。 List comprehensions are for building lists.
列表推导式用于构建列表。 You could do something hacky, like this:
你可以做一些骇人听闻的事情,像这样:
>>> junk = [print("\r") or [print("* ",end='') for j in range(0, i+1)] for i in range(0, n)]
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
>>> junk
[[None], [None, None], [None, None, None], [None, None, None, None], [None, None, None, None, None], [None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None, None]]
But you create a needless list of junk.但是你创建了一个不必要的垃圾列表。 Don't do it.
不要这样做。
You can create one line of n times the *
symbol by using join
on something similar to a list comprehension, namely a generator expression:您可以通过在类似于列表推导式(即生成器表达式)上使用
join
来创建一行n倍*
符号:
>>> ''.join('*' for _ in range(5))
'*****'
You can create output consisting of multiple lines by joining the individual lines with the newline character '\\n'
(as opposed to the empty string ''
like before):您可以通过使用换行符
'\\n'
连接各个行来创建由多行组成的输出(与之前的空字符串''
相反):
>>> lines = '\n'.join(['hello', 'world'])
>>> lines
'hello\nworld'
>>> print(lines)
hello
world
I'll leave combining the two as an exercise for you.我将把两者结合起来作为练习。
Keep the print()
statement out of the comprehension by returning something from the comprehension that will print as a pyramid:通过从理解中返回一些将打印为金字塔的东西,将
print()
语句排除在理解之外:
n = 10
print(*['*' * i for i in range(1, n + 1)], sep='\n')
OUTPUT输出
> python3 test.py
*
**
***
****
*****
******
*******
********
*********
**********
>
You can just write this, you no need to mention sep='\\n'
写这个就可以了,不用提
sep='\\n'
n = 5
print('\n'.join(['*'*i for i in range(1,n+1)]))
Note: You should always start your range from
1
ton+1,
otherwise it will skip your first iteration.注意:你应该总是从
1
到n+1,
开始你的范围n+1,
否则它会跳过你的第一次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.