首页 > 解决方案 > 如何分发列表?

问题描述

假设我有两个如下列表:

list1 = ['A','B','C']
list2 = ['a[3]','a[2]','a[1]','a[0]','b[3]','b[2]','b[1]','b[0]','c[3]','c[2]','c[1]','c[0]']

并且有如下输入文本('random_text' 是与数据无关的内容):

random_text

put A_upper_case_here    
random_text    
put a[3]_lower_case_here    
random_text
put a[2]_lower_case_here    
random_text
put a[1]_lower_case_here    
random_text
put a[0]_lower_case_here    
random_text
put B_upper_case_here    
random_text    
put b[3]_lower_case_here    
random_text
:
put c[0]_lower_case_here    
random_text

我想要的是将列表的每个数据放入输入文本中,如下所示并将其提取到输出:

random_text

put A_upper_case_here 
A
random_text    
put a[3]_lower_case_here    
a[3]
random_text
put a[2]_lower_case_here
a[2]    
random_text
put a[1]_lower_case_here
a[1]    
random_text
put a[0]_lower_case_here
a[0]   
random_text
put B_upper_case_here
B    
random_text    
put b[3]_lower_case_here
b[3]    
random_text
:
put c[0]_lower_case_here
c[0]    
random_text

上面是一个简单的案例,所以,我尝试了一个for循环,以防金额大,并将案例分为“大写”和“小写”,如下所示:

list1 = ['A','B','C']
list2 = ['a[3]','a[2]','a[1]','a[0]','b[3]','b[2]','b[1]','b[0]','c[3]','c[2]','c[1]','c[0]']

with open('input.txt', 'r') as f, open('output.txt', 'w') as fnw:
    for line in f.readlines():
        if "upper_case" in line:
            f.write("\n {0}" .format(list1))

        elif "lower_case" in line:
            f.write("\n {0}" .format(list2))

        else: 
            f.write(line)
     fnw.write(f)
     fnw.close() 

但是,由于现在我可能是 python 的初学者,它根本不起作用。我该如何处理?

标签: pythonpython-3.xlistfor-loop

解决方案


如果我正确理解了您的问题,则此代码可以满足您的要求:


import re

list1 = ['A','B','C']
list2 = ['a[3]','a[2]','a[1]','a[0]','b[3]','b[2]','b[1]','b[0]','c[3]','c[2]','c[1]','c[0]']

upper_set = set(list1)
lower_set = set(list2)

pattern = re.compile('^put (.*)_(lower|upper)_case_here\s*$')

with open('input.txt', 'r') as f, open('output.txt', 'w') as fnw:
    for line in f.readlines():
        fnw.write(line) # This copies all input to the output, remove this line if you don't want that
        match = pattern.search(line)
        print(line, match)
        if match:
            content = match.group(1)
            case = match.group(2)

            case_set = upper_set if case == 'upper' else lower_set

            if content in case_set:
                fnw.write(content)
                fnw.write('\n')
            

它使用正则表达式来检查一行是否格式正确并提取相关部分。正则表达式需要一些时间来学习,但我将解释这里使用的每个部分 ( ^put (.*)_(lower|upper)_case_here\s*$) 的作用:

  • ^意味着什么都不能出现在'put'. 没有这个,像这样的行'random_text...put A_upper_case_here'会被接受
  • put 匹配文本'put '
  • (.*)完全匹配任何文本并在组中捕获它1
  • _匹配文本'_'
  • (lower|upper)匹配lowerupper并在捕获组中捕获它2
  • _case_here匹配文本
  • \s*匹配任意数量的任意空格。这*意味着它允许任何数量的它。它包括每行末尾的新行以及示例输入文本中行末尾的额外空格。
  • $这标志着输入的结束。如果这不在这里,则'put a[0]_lower_case_hereafter'可以接受类似的行。

upper_set = set(list1)和行将您的lower_set = set(list2)列表转换为集合。集合就像一个列表,但没有顺序,并且检查某物是否在集合内比检查它是否在列表中要快得多。由于我们进行了大量此类检查,因此在这里使用集合是正确的数据结构。

其他变化:

  • f以只读模式打开并引用输入文件,因此不应写入 - 仅fnw写入。
  • fnw.close()不需要,因为该with语句已经为您做到了。

推荐阅读