[英]How to fix 'TypeError: unhashable type: 'list' error?
為了讓我的程序開始運行,我需要取一個字符串並將數字插入到特定位置。 我已經有代碼可以做到這一點。 我現在需要做的是獲取它,以便程序將對列表中的每個項目(這是一個數字)執行此操作。 我使用了一個內聯 for 循環並得到了一個“TypeError: unhashable type: 'list' 錯誤。 我也想把結果放在一個列表中。
我已經做的是編寫代碼來替換我正在使用的原始字符串中的數字作為概念證明。 但是,當我嘗試在前面的代碼中插入一個循環時,我得到了那個錯誤。 代碼如下:
s = '<button id="qty_plus_cartline_change_1221067058" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>'
new_string = re.sub('\d+', 'new number', s,1)
print(new_string)
這是概念證明,可以按照我想要的方式替換數字。
updated_list = []
new_string = re.sub('\d+', [i for i in list], s,1)
updated_list.append(new_string)
print(updated_list)
以上是我試圖使用的代碼,以便用現有列表中的所有數字替換字符串。
結果,我正在尋找的是一個新字符串,其中包含列表(列表)中每個項目的新更新編號。 以供參考:
list = [1111111111,2222222222,3333333333,4444444444]
這意味着,我正在尋找的是:
['<button id="qty_plus_cartline_change_1111111111" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_2222222222" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_3333333333" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>', '<button id="qty_plus_cartline_change_4444444444" type="button" class="quantity_plus " data-component="quantitybox.inc">+<span class="offscreen">Increase the Quantity 1</span></button>']
任何幫助是極大的贊賞!
您應該在列表re.sub
調用re.sub
,而不是相反。 另外,不要命名變量list
因為它會影響內置函數list
。 在以下示例中,我已將其重命名為lst
:
updated_list = [re.sub('\d+', str(i), s, 1) for i in lst]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.