将python列表拆分为不带库的行

2024-04-25 00:50:49 发布

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

我有一个Python中的字母列表,我想将其拆分为偶数长度的块,这些块将显示为行。出于教学方面的原因,我不想使用和图书馆(包括numpy或Pandas)。不,这不是家庭作业问题——我在自学。你知道吗

在R中,我将使用一个向量而不是一个列表;一个简单的as.matrix(vector, ncol = n)就可以做到这一点。Python中是否有对等的语言?你知道吗

举个例子,我在其他答案的基础上尝试了以下方法:

alphabet = map(chr, range(65, 91))
print alphabet
> ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def chunks(l, n):
    n = max(1, n)
    return [l[i:i + n] for i in range(0, len(l), n)]

print chunks(alphabet, 4)
> [['A ', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P'], ['Q', 'R', 'S', 'T'], ['U', 'V', 'W', 'X'], ['Y', 'Z']]

这通常是可行的,但我希望输出如下所示:

[['A ', 'B', 'C', 'D'], 
['E', 'F', 'G', 'H'], 
['I', 'J', 'K', 'L'], 
['M', 'N', 'O', 'P'], 
['Q', 'R', 'S', 'T'], 
['U', 'V', 'W', 'X'],
 ['Y', 'Z']]

理想情况下,我将扩展该功能以生成“最正方形”的矩形。也就是说,我会抽出列表长度的最高因子,然后用较小的数字作为列数,所以如果可能的话,我想要一个非常概括的答案。你知道吗


Tags: 答案numpypandas列表图书馆字母range原因
2条回答

我将定义一个新函数,逐行打印块。你知道吗

def print_chunks(chunk_result):
    for chunk in chunks:
        print(chunk)

我相信这会给你你想要的结果。你知道吗

要获得切片行为,您需要实现自己的类。我很快就想出了一些能让你开始学习的东西,但我没有彻底检查。你知道吗

class Chunk(object):
    """docstring for Chunk"""
    def __init__(self, l, n):
        super(Chunk, self).__init__()
        self.chunks = self.chunk(l, n)

    def __repr__(self):
        """
        Done in a non-standard way.
        """
        for chunk in self.chunks:
            print(chunk)

    def __getitem__(self, key):
        if isinstance(key, slice):
            return self.chunks[i] for i in xrange(*key.indices(len(self.chunks)))
        elif isinstance(key, int):
            if key < 0:
                key += len(self.chunks)
            if key >= len(self):
                raise IndexError('The index {0} is out of range'.format(key))
            return self.chunks[i]

为了便于参考,我查看了以下SO帖子: Python: Implementing slicing in __getitem__

只需使用“打印以下内容中的每个列表”:

for line in chunks(alphabet, 4):
    print line

相关问题 更多 >