有一个我需要运行的ID列表,并使用切片替换某些字符

2024-10-02 16:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个标识符列表,每个标识符是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

Tags: in列表forlenif字母数字标识符
1条回答
网友
1楼 · 发布于 2024-10-02 16:22:13

您得到的错误是因为字符串不支持项分配

如果您想在I上迭代并逐个字符地修改它,您需要在遍历它时创建一个新字符串,类似于

if len(I) <= 8:
    new_I = ''
    for i in I:
        if i in mapA2_dict:
            new_I.append(mapA2_dict[i])
        else:
            new_I.append(i)

不过,基于您所做的事情,一种更干净的方法是使用translation table

这将把代码转换成类似于

import string
mapA2 = string.maketrans(from="abc", to="def")
# This equates to translating `a` to `d`, `b` to `e`, `c` to `f`
if len(I) <= 8:
    I = I.translate(mapA2)

相关问题 更多 >