将一个项目替换为列表中的一个项目

时间:2016-12-10 20:02:44

标签: python python-2.7 list replace sequence

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

seq = '01202112'

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

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

list_seq = [01001110, 01101110]

通过使用.replace(),我可以遍历l,但我想知道是否有更多的pythonic方式来获取list_seq

4 个答案:

答案 0 :(得分:4)

我可能会这样做:

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在评论中注意到我曾经假设我总是有足够的字符来填充!如果我们用完了,我们将按照他的建议保留原始角色,但修改这种方法以表现不同是直截了当的,留给读者练习。 : - )

答案 1 :(得分:1)

[''.join([str(next(digit, 0)) if x is '2' else x for x in seq])
 for digit in map(iter, l)]

答案 2 :(得分:0)

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

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] 

答案 3 :(得分:-1)

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

def grunch(s, tu):
    it = map(str,tu)
    return ''.join(next(it) if c=='2' else c for c in s)

list_seq = [grunch(seq,tu) for tu in li]