列表中插入改变间隔

2024-06-08 05:23:45 发布

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

我不知道该怎么称呼这个问题,如果一个mod可以更改标题以更好地反映这个问题,请尝试一下。如果你不是国防部的话,请随意评论名字建议。谢谢:)

我正在尝试创建一个raid5模拟,使用Python列表作为hdd。我已经成功地模拟了raid4,其中所有奇偶校验都在一个磁盘上(参见this CodeReview post)。现在我尝试在所有磁盘上分配奇偶校验

RAID 4:奇偶校验在一个磁盘上,RAID 5:奇偶校验分布

RAID 4 has the parity on one diskRAID 5 has the parity distibuted across all disks

我不知道如何将奇偶校验正确地插入到列表中

给定字节列表:
b = [104, 101, 121, 32, 116, 104, 101, 114, 101, 32, 66, 111, 98, 98, 121, 33]

我需要它在hdd(hdd[0]-hdd[3])之间平均分配,在末尾用0填充
hdd[0] = [104, 32, 101, "p", 98, 33 ]
hdd[1] = [101, 116, "p", 32, 98, 0 ]
hdd[2] = [121, "p", 114, 66, 121, "p"]
hdd[3] = ["p", 104, 101, 111, "p", 0 ]

我认为这样做的方法是在将列表拆分到hdd之前将"p"插入到列表中

我不知道怎么做,因为在它插入一个之后,列表会改变,在插入第4个"p"之后,它会重置回第一个位置

我已经尝试过使用以下代码插入"p": 在这个例子中,hdd_num = 4(它是hdd的数量)

for i, x in enumerate(input_bytes):
    row = i // (hdd_num - 1)
    hdd = hdds[i % hdd_num]
    if hdd[0] == row:
        input_bytes.insert(i+1, "p")
    hdds[i % hdd_num].append(x)

Tags: mod标题列表inputbytes评论名字num
2条回答

我的方法是将代码分成可管理的部分,这些部分可以单独测试和推理。这里有一个建议

def grabChunkOfBytes(byteArray, noChunks):
    chunks = []
    for byte in byteArray:
        chunks.append(byte)
        if len(chunks) == noChunks:
            yield chunks
            chunks = []

    # If the total number of bytes is not divisible by number of disks, 0-fill
    while len(chunks) < noChunks:
        chunks.append(0)
    yield chunks

def computeChecksum(chunks):
    return 'p'  # Your function

def writeChunkToHDDs(chunks, HDDs):
    [hdd.append(part) for hdd, part in zip(HDDs, chunks)]


b = [104, 101, 121, 32, 116, 104, 101, 114, 101, 32, 66, 111, 98, 98, 121, 33, ]
hdds = [[], [], [], []]
totalHDDs = len(hdds)

for i, chunk in enumerate(grabChunkOfBytes(b, totalHDDs - 1)):
    checksum = computeChecksum(chunk)
    chunk.insert(i % totalHDDs, checksum)
    writeChunkToHDDs(chunk, hdds)

from pprint import pprint
pprint(hdds)

谢谢你让我走上正确的道路@Andrei。我最终得到了以下代码:

# make blank hdds (with their parity index)
hdds = [[i] for i in range(hdd_num)]

i = 0
# while there are still bytes to store
while len(input_bytes):
    # pop the row from the list
    row = input_bytes[:hdd_num - 1]
    del input_bytes[:hdd_num - 1]

    # add 0s if there aren't enough elements
    while len(row) < hdd_num - 1:
        row.append(0)

    # add the XOR result in the right place
    row.insert(i % hdd_num, xor(row))

    # insert the values into the HDDs
    for j, x in enumerate(row):
        hdds[j].append(x)

    i += 1

它使用了您的想法,即获取每行中的值,将异或结果插入行中的正确位置,然后将它们添加到硬盘中。谢谢

xor函数如下:

def xor(self, *to_xor):
    """Performs XOR on parameters, from left to right."""
    # if passed a list as it's only argument, xor everything in it
    if len(to_xor) == 1 and \
            isinstance(to_xor[0], (list, tuple, types.GeneratorType)):
        to_xor = to_xor[0]

    x = 0
    for i in to_xor:
        x ^= i
    return x

相关问题 更多 >

    热门问题