用列表中的一项替换字符串中的一项
Replace one item in a string with one item from a list
我有一个字符串和一个列表:
seq = '01202112'
l = [(0,1,0),(1,1,0)]
我想要一种 pythonic 方式,将每个 '2'
替换为列表 l
中相应索引处的值,以便我获得两个新字符串:
list_seq = [01001110, 01101110]
通过使用 .replace()
,我可以遍历 l
,但我想知道是否有更 pythonic 的方法来获取 list_seq
?
我不知道这个解决方案是否 'more 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]
我可能会这样做:
out = [''.join(c if c != '2' else str(next(f, c)) for c in seq) for f in map(iter, l)]
基本思路是我们调用iter
将l
中的元组变成迭代器。那时,每次我们对它们调用 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 在评论中指出我一直认为我总是有足够的字符来填充!如果我们 运行 退出,我们将按照他的建议保留原始字符,但修改这种方法以使其表现不同是直截了当的,留作 reader 的练习。 :-)
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]
[''.join([str(next(digit, 0)) if x is '2' else x for x in seq])
for digit in map(iter, l)]
我有一个字符串和一个列表:
seq = '01202112'
l = [(0,1,0),(1,1,0)]
我想要一种 pythonic 方式,将每个 '2'
替换为列表 l
中相应索引处的值,以便我获得两个新字符串:
list_seq = [01001110, 01101110]
通过使用 .replace()
,我可以遍历 l
,但我想知道是否有更 pythonic 的方法来获取 list_seq
?
我不知道这个解决方案是否 'more 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]
我可能会这样做:
out = [''.join(c if c != '2' else str(next(f, c)) for c in seq) for f in map(iter, l)]
基本思路是我们调用iter
将l
中的元组变成迭代器。那时,每次我们对它们调用 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 在评论中指出我一直认为我总是有足够的字符来填充!如果我们 运行 退出,我们将按照他的建议保留原始字符,但修改这种方法以使其表现不同是直截了当的,留作 reader 的练习。 :-)
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]
[''.join([str(next(digit, 0)) if x is '2' else x for x in seq])
for digit in map(iter, l)]