如何解决“ TypeError:无法散列的类型:'list”错误?

时间:2019-05-04 00:17:41

标签: python python-3.x

为了使我的程序起步,我需要取一个字符串并将数字插入特定位置。我已经做到了。我现在需要做的就是获取它,以便程序将对列表中的每个项目(即数字)执行此操作。我使用了内联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>']

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您应该在列表理解内调用re.sub,而不是相反。另外,不要命名变量list,因为它会掩盖内置函数list。在以下示例中,我将其重命名为lst

updated_list = [re.sub('\d+', str(i), s, 1) for i in lst]