如何在行和列中显示一长串数字?

时间:2017-09-21 01:03:17

标签: python list for-loop indexing nested

我正在尝试从第一个函数中创建的列表中打印第二个函数中的表。当前代码在打印到控制台时没有正确排列,并且它还按照从左到右的顺序打印到每行,而不是从每列的“从上到下”打印。我不知道在displayPrimes()函数中需要更改什么。

def findPrimes(n):
    prime_list = [2]

    for number in range(3, n, 2):
        if all(number % i != 0 for i in range(2, int(number ** .5) + 1)):
            prime_list.append(number)

    return prime_list

def displayPrimes():
    for row in findPrimes(4027):
        for col in findPrimes(4027):
            product = row * col
            print(product, end = "\t")
            break

# main program
findPrimes(4027)
displayPrimes()

2 个答案:

答案 0 :(得分:2)

ch = sprintf('name: John\nsex: M\n')
ch =
    'name: John
     sex: M
     '

答案 1 :(得分:1)

我有一个初学者可能不太容易理解的解决方案,但它允许您指定列数。

itertools文档中有一个grouper recipe,您可以使用它将可迭代分成n个大小的组/元组。如果您计算出每列有多少项(items_per_column = math.ceil(len(primes)/columns)),您可以将此数字传递给grouper,然后使用此zip技巧转置返回的可迭代:zip(*iterable)。以下是这个成语的演示:

>>> lst = [(1,2,3), (4,5,6)]
>>> list(zip(*lst))
[(1, 4), (2, 5), (3, 6)]

解决方案:

import math
from itertools import zip_longest


def findPrimes(n):
    prime_list = [2]
    for number in range(3, n, 2):
        if all(number % i != 0 for i in range(2, int(number ** .5) + 1)):
            prime_list.append(number)
    return prime_list


def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


def prime_table(number, columns=8):
    """Rearrange the primes into top to bottom columns."""
    primes = findPrimes(number)
    # Figure out how many items fit into one column.
    items_per_column = math.ceil(len(primes)/columns)  # Round up.
    # `grouper` splits the list into tuples of length items_per_column.
    # Then transpose the groups with `zip(*iterable)`, so that
    # the primes are arranged top to bottom.
    return zip(*grouper(primes, items_per_column, ''))


def print_table(rows):
    for row in rows:
        for item in row:
            print('{:>6}\t'.format(item), end='')
        print()


print_table(prime_table(4027))

打印超过10列或非常大的数字会使桌面变得混乱。