total_byte_len = 954
part_size_limit = 250
Result: #[star_byte, end_byte, bytes_in_part] with 0-based index
[[0, 250, 250], [251, 501, 250], [501, 751, 250], [751, 953, 202]]
我已经有了一个功能,但它非常粗糙和不可靠(快速肮脏),它大约有15行,所以我很想知道列表理解/或lambda在这里可以做什么=)
如果你们坚持,这是我的版本: 请注意,我当时并没有考虑过这么多想法,只是尽快运作。 :)弃用通知!:< ==
def to_json(value):
return json.dumps(value)
def getByteRanges(total_byte_len, part_size_limit):
if total_byte_len%part_size_limit == 0: #devides evenly
left_over_part = 0
else:
left_over_part = 1
how_many_parts = roundup(((total_byte_len-(total_byte_len%part_size_limit))/part_size_limit)+left_over_part)
part_size = int(((total_byte_len-(total_byte_len%part_size_limit))/(how_many_parts-left_over_part))) #-1 to not include last part
parts = [x for x in range(how_many_parts)]
ranges = []
for i, obj in enumerate(parts):
start_range = (part_size*i)+1
end_range = part_size*(i+1)+1
if i == 0: #first part
start_range = 0
end_range = part_size
if i == len(parts)-1: #last part
end_range = total_byte_len-1
ranges.append([int(start_range), int(end_range), (int(end_range)-int(start_range))])
return ranges
答案 0 :(得分:2)
详细但可读的版本:
s = []
for p in range(0, total_byte_len, part_size_limit):
last = min(total_byte_len - 1, p + part_size_limit - 1)
s.append([p, last, last - p + 1])
答案 1 :(得分:1)
你的例子是有点关闭(第二部分有251个字节),但这样的工作:
[[x, y - 1, y - x] for x in range(0,total_byte_len, part_size_limit) for y in [min(x + part_size_limit, total_byte_len)]]
你也应该创建一个元组列表。
答案 2 :(得分:1)
您的输出不正确,因为sum([250, 249, 249, 202]) != 954
。
$ python3
>>> def fun(x, y):
... f= lambda i: y if (x-i)>=y else x%y
... return [[i, i+f(i)-1, f(i)] for i in range(0, x, y)]
...
>>> fun(954, 250)
[[0, 249, 250], [250, 499, 250], [500, 749, 250], [750, 953, 204]]