![](/img/trans.png)
[英]Write function mult3() that takes as input a list of integers and prints only the multiples of 3, one per line
[英]a function that takes a list of integers and prints a string of stars which has the length of a value of an integer to the screen
首先,大家好,我是第一次来这里。 无论如何。 我有这个问题,我没有一个真正的方向。:. 我试过这个:
def MyStars(inputList):
l = len(inputList)
ret = []
for x in inputList:
ret.append("* ")
print(ret)
但后来我意识到 output 是一个 * 字符串,它最后是我在原始列表中拥有的整数数......结果是:
['* ', '* ', '* ']
虽然我希望它用于列表 [3,9,7],例如:
*** ********* *******
有人可以帮忙吗? tnx
我不会使用append
而是使用字符串乘法的列表理解:
def MyStars(inputList):
print(' '.join(['*'* i for i in inputList]))
MyStars([3, 9, 7])
output: *** ********* *******
要修复您的代码,您需要 2 个循环,一个用于迭代数字,一个用于 append 您的字符,然后join
您的列表:
def MyStars(inputList):
l = len(inputList)
for x in inputList:
ret = []
for i in range(x):
ret.append('*')
print(''.join(ret), end=' ')
MyStars([3, 9, 7])
注意。 请注意,此版本提供了一个尾随空格。
试试这个代码。
您的代码发生的事情是您接近答案,但您需要使用范围 function 并循环通过 x 将正确数量的星添加到您的列表中。
def MyStars(inputList):
l = len(inputList)
ret = []
for x in inputList:
for i in range(x):
ret.append("*")
ret.append(" ")
for a in ret:
print(a)
如果您只想打印,您可以
print(*("*" * n for n in input_list))
对于input_list = [3, 9, 7]
打印*** ********* *******
<s: str> * <n: int>
将字符串s
乘以n
次,例如"xYZ" * 3
将得到"xYZxYZxYZ"
(在这种情况下"*" * 3
将是"***"
)("*" * n for n in input_list)
input_list
的每个n
创建一个由"*" * n
-s 组成的集合(如果您想多次迭代该集合,这将创建一个只能迭代一次的生成器,您可以创建例如一个列表( [...]
)代替)print(*<iterable>)
打印可迭代的每个项目并用sep
分隔它们(默认情况下是一个空格,这恰好是您想要的,您可以将sep
作为print
参数传递,例如print(*<iterable>, sep="\n")
修复您的解决方案的示例(我还调整了命名以遵循 python 约定):
def my_stars(input_list):
stars_strings = []
for x in input_list:
stars_strings.append("*" * x)
ret = " ".join(stars_strings)
print(ret)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.