如何打印10列中的整数列表?

时间:2015-11-30 02:47:53

标签: python list python-3.x

我知道这可能非常简单,但我很挣扎。我想在对齐的列中打印这个素数列表,每行有10个素数。

我的程序目前在一行中打印所有数字。

prime = []
not_prime = []

for i in range(2,numbers+1):

    if i not in not_prime:
        prime.append(i)

        for x in range(i**2,numbers+1,i):
            not_prime.append(x)

print (*prime, sep=' ')

请帮帮我。谢谢!

1 个答案:

答案 0 :(得分:2)

这种最简单的方法是在您prime的末尾迭代print (*prime, sep=' ')

如果您使用的是 Python 2

# use `numbers = 100` as an example
numbers = 100

prime = []
not_prime = []

for i in range(2,numbers+1):

    if i not in not_prime:
        prime.append(i)

        for x in range(i**2,numbers+1,i):
            not_prime.append(x)

# `enumerate` gives us a tuple of (index, element) in an iterable
for idx, p in enumerate(prime):

    # "{:3d}" is a format string that is similar to the C-style
    # of %X.YA where `X` denotes the character width, `.Y` denotes
    # how many places to display in a floating point number,
    # and `A` denotes the type of what's being printed. Also note,
    # in Python, you don't need to use the `d` in `:3d`, you can just
    # do `{:3}`, but I've included it for your knowledge.
    #
    # the comma says 'don't add a newline after you print this'
    print "{:3d}".format(p),

    # we'll use `idx + 1` to avoid having to deal with the
    # 0-indexing case (i.e., 0 modulo anything is 0)
    if (idx + 1) % 10 == 0:

        # just print a newline
        print

结果:

  2   3   5   7  11  13  17  19  23  29
 31  37  41  43  47  53  59  61  67  71
 73  79  83  89  97

修改

如果您使用的是 Python 3 ,则需要更改:

print "{:3}".format(p),

print ("{:3}".format(p), end="")

并且您想要更改打印换行符的位置

print ()

结果代码是:

# use `numbers = 100` as an example
numbers = 100

prime = []
not_prime = []

for i in range(2,numbers+1):

    if i not in not_prime:
        prime.append(i)

        for x in range(i**2,numbers+1,i):
            not_prime.append(x)

# `enumerate` gives us a tuple of (index, element) in an iterable
# `start=1` tells enumerate to use a 1-based indexing rather than
# 0-based.
for idx, p in enumerate(prime, start=1):

    # "{:3d}" is a format string that is similar to the C-style
    # of %X.YA where `X` denotes the character width, `.Y` denotes
    # how many places to display in a floating point number,
    # and `A` denotes the type of what's being printed. Also note,
    # in Python, you don't need to use the `d` in `:3d`, you can just
    # do `{:3}`, but I've included it for your knowledge.
    #
    # the comma says 'don't add a newline after you print this'
    print ("{:3d}".format(p), end="")

    # if it's a multiple of 10, print a newline
    if idx % 10 == 0:

        # just print a newline
        print ()