繁体   English   中英

如何修复“TypeError: unhashable type: 'list' 错误?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM