首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法以不同的方式编辑列表中同一子字符串的两个实例?

有没有办法以不同的方式编辑列表中同一子字符串的两个实例?
EN

Stack Overflow用户
提问于 2019-07-19 21:10:46
回答 1查看 50关注 0票数 0

我有一个很大的列表,其中包含两个相同的行。对于这个字符串的第一次出现,我想要进行某些编辑,对于第二次,我想要进行不同的编辑。

我尝试使用状态函数以及一些regex的东西,但没有工作。我希望编辑一个列表,它可以采用以下形式:

代码语言:javascript
复制
lots of words
lots of words

Contingency 17 - Reno - Vegas
more words

Contingency 17 - Reno - Vegas
still more

我知道这不是pythonic式的,但我正在寻找一些可以实现以下功能的代码:

代码语言:javascript
复制
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)

希望这将在大型文本文件中以不同的方式编辑字符串的第一个和下一个实例。我需要帮助选择以不同的方式编辑这两行。这方面的输出示例如下:

代码语言:javascript
复制
lots of words
lots of words

Contingency 20 - Reno - Carson City
more words

Contingency 25 - Carson City - Vegas
still more
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-19 21:27:58

尝试:

代码语言:javascript
复制
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')]

这里最大的问题是你必须知道你的模式有多少次出现。如果您不关心这一点,并且您所要做的就是将一个函数应用于第一次出现的情况,并将不同的函数应用于所有后续出现的情况,请使用状态标志:

代码语言:javascript
复制
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()语句。这是非常脆弱的,而且有很多模式会很麻烦,所以你可以考虑函数的查找字典:

代码语言:javascript
复制
lookup_fun_dict = {'b': [first_fun, second_fun], 'c': [first_fun, third_fun]}

如果操作很简单,我可能也会使用lambdas而不是函数。

这是相当脆弱的,我相信其他人会想出一个优雅的解决方案。如果pattern出现的次数很多,并且您对其应用的操作代价很高,那么您可以只使用一个静态值将pattern替换为,或者至少将其记为内存。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57113227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档