簡體   English   中英

替換 Python 列表中的某些值

[英]Replacing certain values in Python List

我創建了一個列表,用於顯示帶有像素值的黑白(二進制)圖像。 但是,對於我正在運行的計算,我無法使用黑色像素表示的 0。 我一直在嘗試使用以下代碼將 0 轉換為 1,但盡管沒有產生錯誤,但它不起作用:

from PIL import Image

img = Image.open('C:/Users/binary.png', 'r')  
WIDTH, HEIGHT = img.size

data = list(img.getdata())  # convert image data to a list of integers
data = [data[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

for (i, item) in enumerate(data):
    if item == 0:
        data[i] = 1

for row in data:
    print(' '.join('{:3}'.format(value) for value in row))

值得注意的是,當我嘗試“item = 255”時,出現以下錯誤:“TypeError: '<' not supported between 'list' and 'int'”

但是這個錯誤對我來說沒有意義,因為當我輸入(數據)時,我得到了列表輸出

data是一個列表列表,你需要嵌套循環。

for row in data:
    for i, value in enumerate(row):
        if value == 0:
            row[i] = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM