简体   繁体   English

循环打印列表格式化

[英]While Loop Print List formatting

I wanted to create a list of factors from any given number only using the formula below. 我想只使用下面的公式从任何给定的数字创建一个因子列表。 I am not allowed to use list therefore, I have imitate using strings as follows: 因此我不允许使用列表,我模仿使用字符串如下:

for example and lets say we choose num=12: 例如,让我们说我们选择num = 12:

def factors(num):
    i=1 
    while i <= num :
        if num % i == 0:
            print i

        i = i + 1

this code prints: 此代码打印:

1
2
3
4
6
12

Without using lists, for loops, int, function and can only use strings, 不使用list,for循环,int,function,只能使用字符串,

how do i format the loop outputs to make it look like this?: 如何格式化循环输出以使其看起来像这样?:

[1, 2, 3, 4 ,6 ,12]

I tried doing this first: 我先尝试这样做:

num = 12
i = 1
while i <= num :
    if num % i == 0:
        a=str("[")+str(i)+", "+str("]")
        print a

    i = i + 1

This prints: 这打印:

[1, ]
[2, ]
[3, ]
[4, ]
[6, ]
[12, ]

Can anyone help or suggest where I can put that print state or how do i modify it? 任何人都可以帮助或建议我可以将打印状态放在哪里或如何修改它? Thanks! 谢谢!

def factors(num):
    i=1
    result="["
    while i <= num :
        if num % i == 0:
            result=result+str(i)+","
        i+=i

    result=result[:-1]+"]"
    print result

factors(12)

Output > [1,2,4] 输出> [1,2,4]

you can use use a print statement that ends with a comma to not insert a new line when a second print statement is used then you just need to make sure the first time in prints "[" and the last time it prints "]" 您可以使用以逗号结尾的print语句,以便在使用第二个print语句时不插入新行,那么您只需要确保第一次打印“[”并且最后一次打印“]”

for example 例如

print "hello ",
print "world"

would return >>>hello world 会回归>>>你好世界

the code would look something like this 代码看起来像这样

def factors(num):
    i=1 
    while i <= num :
        if i == 1:
            if num % i == 0:
                print "[",
            else:
                 print "[",
        if i == num:
            print "%s]"%(i)
        elif num % i == 0:
            if i == num:
               print i,"]"
            else:
                print "%s,"%(i),




        i = i + 1

You can concatenate each str(i) to string a by += , 您可以将每个str(i)到字符串a by +=

def factors(num):
    i = 1
    a = "["
    while i < num :
        if num % i == 0:
            a+=str(i)+", "
        i = i + 1
    print(a + str(num) + str("]"))

factors(12)

Output: 输出:

   [1, 2, 3, 4, 6, 12]
def factors(num):
    i = 1
    factors = []
    while i <= num:
        if num % i == 0:
            factors.append(i)

    i += 1

    print factors

factors(12)

This adds all the factors to a table called factors, and then when all the factors are added, the table factors is printed out. 这会将所有因子添加到名为factors的表中,然后在添加所有因子时打印出表因子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM