我正在尝试计算可变大小数组的原点和偏移量并将它们存储在字典中。这是我实现这一目标的可能的非 pythonic 方式。我不确定我是否应该使用 map、lambda 函数或列表理解来使代码更符合 pythonic。
本质上,我需要根据总大小切割数组 block ,并将 xstart、ystart、x_number_of_rows_to_read、y_number_of_columns_to_read 存储在字典中。总大小是可变的。我不能将整个数组加载到内存中并使用 numpy 索引,否则我肯定会这样做。原点和偏移量用于将数组放入 numpy。
intervalx = xsize / xsegment #Get the size of the chunks
intervaly = ysize / ysegment #Get the size of the chunks
#Setup to segment the image storing the start values and key into a dictionary.
xstart = 0
ystart = 0
key = 0
d = defaultdict(list)
for y in xrange(0, ysize, intervaly):
if y + (intervaly * 2) < ysize:
numberofrows = intervaly
else:
numberofrows = ysize - y
for x in xrange(0, xsize, intervalx):
if x + (intervalx * 2) < xsize:
numberofcolumns = intervalx
else:
numberofcolumns = xsize - x
l = [x,y,numberofcolumns, numberofrows]
d[key].append(l)
key += 1
return d
我意识到 xrange 不适合移植到 3。
最佳答案
这段代码看起来不错,除了你使用了 defaultdict
。列表似乎是一种更好的数据结构,因为:
- 您的 key 是连续的
- 您正在存储一个列表,其唯一元素是字典中的另一个列表。
你可以做的一件事:
- 使用三元运算符(我不确定这是否会有所改进,但它会减少代码行数)
根据我的一些建议,这是您的代码的修改版本。
intervalx = xsize / xsegment #Get the size of the chunks
intervaly = ysize / ysegment #Get the size of the chunks
#Setup to segment the image storing the start values and key into a dictionary.
xstart = 0
ystart = 0
output = []
for y in xrange(0, ysize, intervaly):
numberofrows = intervaly if y + (intervaly * 2) < ysize else ysize -y
for x in xrange(0, xsize, intervalx):
numberofcolumns = intervalx if x + (intervalx * 2) < xsize else xsize -x
lst = [x, y, numberofcolumns, numberofrows]
output.append(lst)
#If it doesn't make any difference to your program, the above 2 lines could read:
#tple = (x, y, numberofcolumns, numberofrows)
#output.append(tple)
#This will be slightly more efficient
#(tuple creation is faster than list creation)
#and less memory hungry. In other words, if it doesn't need to be a list due
#to other constraints (e.g. you append to it later), you should make it a tuple.
现在要获取数据,您可以执行 offset_list=output[5]
而不是 offset_list=d[5][0]
关于计算数组偏移量的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549928/