计算机如何获得以下代码的输出?

2024-03-29 11:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法理解代码是如何得到最终结果的。有人能详细地解释一下python是如何解释和执行这个的吗?你知道吗

counts = [5, 2, 5, 2, 2]
for x_count in counts:
    output=""
    for count in range(x_count):
        output+="x"
    print(output)`

结果:

 xxxxx 
 xx
 xxxxx
 xx
 xx

我不懂密码。为什么使用范围内的for count(x\u count)和output+=x会导致“5+x”而不是“xxxxx”?通常要得到“XXXXX”,我们应该使用print(5*“x”),如何使用+给我相同的输出?你知道吗

range函数在这里有什么帮助?你知道吗


Tags: 函数代码in密码foroutputcountrange
3条回答
counts = [5, 2, 5, 2, 2]                    # counts
for x_count in counts:                      # will loop over each element in count
    output=""                               # variable to hold xs
    for count in range(x_count):            # will loop x_count times
        output+="x"                         # 'x' will be appended to output variable
    print(output)                           # output will be printed

你的原始清单

counts = [5, 2, 5, 2, 2]

for count in counts:

这意味着在计数值即它选择第一个元素,然后第二,然后第三 以此类推,直到最后一个元素,即先选择5,然后选择2,以此类推

original = '' # intialise the element 

这将创建一个具有值''的字符串元素

for value in range(count):

range(count)给出范围[0,count)中的值,即从0到0的数字列表 计数(独占)

所以for value in [0,1...count]

所以它将从列表中选择第一个元素的值,然后再选择第二个元素,依此类推

对于要将x添加到original的每个值,都为no,因此for循环将运行count 时间并将x加到original

print(orignal)

将打印原版价值到现在

Colab link for the code

我为你的理解注释了代码。你知道吗

counts = [5, 2, 5, 2, 2] # Counts of X
for x_count in counts: # For every count value
    output="" # Output holds bunch of X 
    # output is reset at every iteration
    for count in range(x_count):
        output+="x" # Populate output with X values for each count
        # + and += concats strings
    print(output) # print output

类似的方法:

counts = [5, 2, 5, 2, 2]
outputs = ["".join(['x'] * count) for count in counts]
for output in outputs:
  print(output)

相关问题 更多 >