我有一个很大的列表,其中包含两个相同的行。对于这个字符串的第一次出现,我想要进行某些编辑,对于第二次,我想要进行不同的编辑。
我尝试使用状态函数以及一些regex的东西,但没有工作。我希望编辑一个列表,它可以采用以下形式:
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发布于 2019-07-19 21:27:58
尝试:
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]}如果操作很简单,我可能也会使用lambdas而不是函数。
这是相当脆弱的,我相信其他人会想出一个优雅的解决方案。如果pattern出现的次数很多,并且您对其应用的操作代价很高,那么您可以只使用一个静态值将pattern替换为,或者至少将其记为内存。
https://stackoverflow.com/questions/57113227
复制相似问题