将字符串中的一项替换为lis中的一项

2024-04-23 21:16:19 发布

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

我有一个字符串和一个列表:

seq = '01202112'

l = [(0,1,0),(1,1,0)]

我想要一种pythonic方法,用列表l中相应索引处的值替换每个'2',以便获得两个新字符串:

list_seq = [01001110, 01101110]

通过使用.replace(),我可以迭代l,但是我想知道有没有更适合于python的方法来获得list_seq?你知道吗


Tags: 方法字符串列表pythonicseqreplacelist
3条回答
[''.join([str(next(digit, 0)) if x is '2' else x for x in seq])
 for digit in map(iter, l)]

我不知道这个解决方案是否“更像Python”,但是:

def my_replace(s, c=None, *other):
        return s if c is None else my_replace(s.replace('2', str(c), 1), *other)


seq = '01202112'
l = [(0,1,0),(1,1,0)]

list_req = [my_replace(seq, *x) for x in l] 

我可能会这样做:

out = [''.join(c if c != '2' else str(next(f, c)) for c in seq) for f in map(iter, l)]

基本思想是调用iterl中的元组转换为迭代器。在这一点上,每次我们调用next,我们就得到下一个需要使用的元素,而不是'2'。你知道吗

如果这过于紧凑,逻辑可能更容易作为一个函数来阅读:

def replace(seq, to_replace, fill):
    fill = iter(fill)
    for element in seq:
        if element != to_replace:
            yield element
        else:
            yield next(fill, element)

给予

In [32]: list(replace([1,2,3,2,2,3,1,2,4,2], to_replace=2, fill="apple"))
Out[32]: [1, 'a', 3, 'p', 'p', 3, 1, 'l', 4, 'e']

感谢@DanD在评论中指出,我一直以为我会有足够的字符来填充!如果我们用完了,我们会按照他的建议保留原来的角色,但是修改这个方法来表现不同是很简单的,留给读者作为练习。:-)

相关问题 更多 >