![](/img/trans.png)
[英]Find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found
[英]Is there a way to edit two instances of the same sub-string in a list differently?
我有一个包含两个相同行的大列表。 对于该字符串的第一次出现,我想进行某些编辑,对于第二个字符串,我想进行不同的编辑。
我试着使用状态功能以及一些正则表达式的东西而没有工作。 我正在寻找一个可以采用以下形式的列表:
lots of words
lots of words
Contingency 17 - Reno - Vegas
more words
Contingency 17 - Reno - Vegas
still more
我知道这不是pythonic,但是我正在寻找一些本质上可以做到的代码:
for line in file.readlines()
if first.("Contingency 17") in line:
#do stuff (I know how to do this section)
elif next.("Contingency") in line:
#do other stuff (I know this as well)
else:
file_out.write(line)
希望这将在大型文本文件中以不同方式编辑字符串的第一个和下一个实例。 我需要选择两行以不同方式进行编辑的帮助。 输出示例如下:
lots of words
lots of words
Contingency 20 - Reno - Carson City
more words
Contingency 25 - Carson City - Vegas
still more
尝试:
def fun_to_apply_to_first_line(line):
return line.upper()
def fun_to_apply_to_second_line(line):
return 2*line
list_of_lines = ['a', 'b', 'c', 'b', 'd']
pattern = 'b'
funlist = [fun_to_apply_to_first_line, fun_to_apply_to_second_line]
new_list = []
for line in list_of_lines:
value = line
if line == pattern:
fun = funlist.pop(0)
value = fun(line)
new_list.append(value)
print(list(zip(list_of_lines, new_list)))
>>> [('a', 'a'), ('b', 'B'), ('c', 'c'), ('b', 'bb'), ('d', 'd')]
这里最大的问题是您必须知道您的模式出现了多少次。 如果您对此并不在意,并且只想对第一个事件应用一个函数,然后对所有后续事件应用一个不同的函数,请使用状态标志:
def fun_to_apply_first(line):
return line.upper()
def fun_to_apply_rest(line):
return 2*line
list_of_lines = ['a', 'b', 'c', 'b', 'd', 'b', 'b']
pattern = 'b'
is_first = True
new_list = []
for line in list_of_lines:
value = line
if line == pattern:
value = fun_to_apply_first(line) if is_first else fun_to_apply_rest(line)
new_list.append(value)
print(list(zip(list_of_lines, new_list)))
>>> [('a', 'a'), ('b', 'B'), ('c', 'c'), ('b', 'B'), ('d', 'd'), ('b', 'B'), ('b', 'B')]
显然最后没有print()语句。 这非常脆弱,并且会麻烦很多模式,因此您可以考虑函数的查询命令:
lookup_fun_dict = {'b': [first_fun, second_fun], 'c': [first_fun, third_fun]}
如果操作很简单,我也可能会使用lambda代替函数。
这非常脆弱,我相信其他人会想到一个优雅的解决方案。 如果出现pattern
次数非常多,并且您对其应用的操作非常昂贵,则可以仅使用静态值来替换pattern
,或者至少将其记住。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.