我有一个标识符列表,每个标识符是8位数字,我需要循环使用6个dict,并用不同的字母和数字替换这些id中的片段
我成功地得到了第一个正确的答案,但循环的下一步是给我带来问题。这是我的密码:
for I in ID:
if I[:3] in mapA_dict:
for inp in mapA_dict:
I = I.replace(inp, mapA_dict[inp])
print I
if len(I) <= 8:
for I[0] in mapA2_dict:
for inp in mapA2_dict:
I = I.replace(inp, mapA2_dict[inp])
print I
我得到了一个错误:
TypeError Traceback (most recent call last)
<ipython-input-22-49924532d1ff> in <module>()
11 # print I
12 if len(I) <= 8:
---> 13 for I[0] in mapA2_dict:
14 for inp in mapA2_dict:
15 I = I.replace(inp, mapA2_dict[inp])
TypeError: 'str' object does not support item assignment
您得到的错误是因为字符串不支持项分配
如果您想在
I
上迭代并逐个字符地修改它,您需要在遍历它时创建一个新字符串,类似于不过,基于您所做的事情,一种更干净的方法是使用translation table
这将把代码转换成类似于
相关问题 更多 >
编程相关推荐