![](/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.