首页 > 解决方案 > 在 Python 中对多个变量进行操作的最佳方式?

问题描述

我有一个图像处理问题,例如:

rgb_clean, rgb_noisy, raw_clean, raw_noisy, pattern = dataset[i]

rgb_clean = imread(rgb_clean)
rgb_noisy = imread(rgb_noisy)
raw_clean = loadmat(raw_clean)["x"]
raw_noisy = loadmat(raw_noisy)["x"]
pattern = np.array([c for c in pattern]).reshape((2, 2))

# normalize
rgb_clean = rgb_clean.astype(np.float32) / 255
rgb_noisy = rgb_noisy.astype(np.float32) / 255
raw_clean = raw_clean.astype(np.float32) / 255
raw_noisy = raw_noisy.astype(np.float32) / 255

# demosaick
raw_clean = debayer(raw_clean, pattern=pattern)
raw_noisy = debayer(raw_noisy, pattern=pattern)

# rotate
k = np.random.randint(4)
rgb_clean = np.rot90(rgb_clean, k=k)
rgb_noisy = np.rot90(rgb_noisy, k=k)
raw_clean = np.rot90(raw_clean, k=k)
raw_noisy = np.rot90(raw_noisy, k=k)
pattern = np.rot90(pattern, k=k)
...

由于担心拼写错误,我尝试重构重复的代码,但没有什么让我满意。

# Style 1: list comprehension
rgb_clean, rgb_noisy, raw_clean, raw_noisy = [
    x.astype(np.float32) / 255
    for x in (rgb_clean, rgb_noisy, raw_clean, raw_noisy)]

# Style 2: map
raw_clean, raw_noisy = map(lambda x: debayer(x, pattern=pattern), (raw_clean, raw_noisy))

# Style 3: list comprehension but more readable
k = np.random.randint(4)
targets = rgb_clean, rgb_noisy, raw_clean, raw_noisy, pattern
targets = [np.rot90(x, k=k) for x in targets]
rgb_clean, rgb_noisy, raw_clean, raw_noisy, pattern = targets

# Style 4: simple for-loop
v_flip, h_flip = np.random.randint([2, 2])
for x in ["rgb_clean", "rgb_noisy", "raw_clean", "raw_noisy", "pattern"]:
    if v_flip:
        vars()[x] = np.flip(vars()[x], axis=0)
    if h_flip:
        vars()[x] = np.flip(vars()[x], axis=1)

样式 1~3 必须写重复的变量名,样式 4 应该将变量称为字符串,因为 Python 中没有“引用调用”的概念(据我所知)。

我也考虑过直接访问列表,但是很难推断要使用哪个变量。

data = dataset[i]
...
k = np.random.randint(4)
data[0:4] = [x.astype(np.float32) / 255 for x in data[0:4]]
data[2:4] = [debayer(x, pattern=data[4]) for x in data[2:4]]
data[0:5] = [np.rot90(x, k=k) for x in data[0:5]]

问题:Python 有没有最可取、最易读的风格?还是我应该对初始代码感到满意?


更新:对不起,愚蠢的问题,我将每个代码都更改为使用 dict。

data = dataset[i]
data["rgb_clean"] = imread(data[0])
data["rgb_noisy"] = imread(data[1])
data["raw_clean"] = loadmat(data[2])["x"]
data["raw_noisy"] = loadmat(data[3])["x"]
data["pattern"] = np.array([c for c in data[4]]).reshape((2, 2))

for x in ["rgb_clean", "rgb_noisy", "raw_clean", "raw_noisy"]:
    data[x] = data[x].astype(np.float32) / 255

for x in ["raw_clean", "raw_noisy"]:
    data[x] = debayer(data[x], pattern=data["pattern"])
...

标签: pythonvariablespass-by-referenceconventions

解决方案


推荐阅读