简体   繁体   中英

How to fix 'TypeError: unhashable type: 'list' error?

In order to get my program off the ground I need to take a string and insert numbers into a particular position. I have code that does that already. What I need to do now, is get it so the program will do that for every item (which is a number) in a list. I used an inline for loop and have gotten a 'TypeError: unhashable type: 'list' error. I also want to put the results in a list.

What I've already done is write the code that will replace the numbers in the original string that I am working with as a proof of concept. However, when I try to insert a loop into the previous code, I get that error. The code is as follows:

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)

That is the proof of concept that works to replace the numbers the way I want.

updated_list = []
new_string = re.sub('\d+', [i for i in list], s,1)
updated_list.append(new_string)
print(updated_list)

Above is the code I'm trying to employ in order to replace the string with all of the numbers in the existing list.

What I'm looking for as a result is a new string with the new updated number for each item in the list (list). For reference:

list = [1111111111,2222222222,3333333333,4444444444]

This means, what I'm looking for is this:

['<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>']

Any help is greatly appreciated!

You should call re.sub inside a list comprehension, not the other way around. Also, don't name a variable list since it would shadow the built-in function list . I've renamed it to lst in the following example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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