替换python字符串/lis中索引列表中的字符

2024-10-01 00:23:20 发布

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

我有一本字典如下:

s_dict = {'s' : 'ATGCGTGACGTGA'}

我想把作为字典中键's'的值存储在位置4、6、7和10的字符串改为h、k、p和r

pos_change = {'s' : ['4_h', '6_k', '7_p', '10_r']}

我可以这样想:

for key in s_dict:
    for position in pos_change[key]:
        pos = int(position.split("_")[0])
        char = position.split("_")[1]
        l = list(s_dict[key])
        l[pos]= char
        s_dict[key] = "".join(l)

输出:

s_dict = {'s': 'ATGChTkpCGrGA'}

这工作得很好,但我实际的s_dict文件大约是1.5gb。有没有更快的方法来替换字符串或列表中特定索引处的字符列表?你知道吗

谢谢!你知道吗


Tags: key字符串inpos列表for字典position
2条回答

以下是我对你的有趣问题的看法:

s_dict = {'s' : 'ATGCGTGACGTGA'}    
pos_change = {'s' : ['4_h', '6_k', '7_p', '10_r']}

# 1rst change `pos_change` into something more easily usable
pos_change = {k: dict(x.split('_') for x in v) for k, v in pos_change.items()}
print(pos_change)  # {'s': {'4': 'h', '6': 'k', '7': 'p', '10': 'r'}}

# and then... 
for k, v in pos_change.items():
  temp = set(map(int, v))
  s_dict[k] = ''.join([x if i not in temp else pos_change[k][str(i)] for i, x in enumerate(s_dict[k])])

print(s_dict)  # {'s': 'ATGChTkpCGrGA'}

作为解决方案的一个选项,您可以使用s_dict['s'] = '%s%s%s' % (s_dict['s'][:pos], char, s_dict['s'][pos+1:])而不是do list和join

In [1]: s_dict = {'s' : 'ATGCGTGACGTGA' * 10}
   ...: pos_change = {'s' : ['4_h', '6_k', '7_p', '10_r']}
   ...: 
   ...: def list_join():
   ...:     for key in s_dict:
   ...:         for position in pos_change[key]:
   ...:             pos = int(position.split("_")[0])
   ...:             char = position.split("_")[1]
   ...:             l = list(s_dict[key])
   ...:             l[pos]= char
   ...:             s_dict[key] = "".join(l)
   ...: 
   ...: def by_str():
   ...:     for key in s_dict:
   ...:         for position in pos_change[key]:
   ...:             pos = int(position.split("_")[0])
   ...:             char = position.split("_")[1]
   ...:             values = s_dict['s'][:pos], char, s_dict['s'][pos+1:]
   ...:             s_dict['s'] = '%s%s%s' % values
   ...:             

In [2]: %timeit list_join()
11.7 µs ± 191 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [3]: %timeit by_str()
4.29 µs ± 46.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

相关问题 更多 >