You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:编写接收整数列表并输出对应长度星号字符串的Python函数

Fixing Your Star Generator Function

Hey there! I see where the issue is with your code—right now, you're appending the same fixed string "* " every time, regardless of the integer value in your input list. That's why you end up with one star per list element instead of stars matching each number's length.

Let's adjust your function to get the desired output:

def MyStars(inputList):
    ret = []
    for x in inputList:
        # Multiply the asterisk by x to get the correct length of stars
        ret.append("*" * x)
    # Join the list elements with spaces and print the final result
    print(" ".join(ret))

How this works:

  • Instead of adding a fixed "* " each loop, we use "*" * x—Python lets you multiply a string by an integer to repeat it that many times. For example, if x is 3, this gives you "***".
  • After building the list of star strings, we use " ".join(ret) to combine all elements into a single string separated by spaces, then print that (instead of printing the raw list structure).

Testing with your example:

If you call MyStars([3,9,7]), it will output exactly what you want:

*** ********* *******

You could also make this even more concise with a list comprehension if you prefer:

def MyStars(inputList):
    print(" ".join(["*" * x for x in inputList]))

This does the same job in fewer lines—building the list of star strings directly inside the join call.

内容的提问来源于stack exchange,提问作者Ethan Yaacobov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:42:42