python - 如何分发列表?
问题描述
假设我有两个如下列表:
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 的初学者,它根本不起作用。我该如何处理?
解决方案
如果我正确理解了您的问题,则此代码可以满足您的要求:
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)
匹配lower
或upper
并在捕获组中捕获它2
_case_here
匹配文本\s*
匹配任意数量的任意空格。这*
意味着它允许任何数量的它。它包括每行末尾的新行以及示例输入文本中行末尾的额外空格。$
这标志着输入的结束。如果这不在这里,则'put a[0]_lower_case_hereafter'
可以接受类似的行。
upper_set = set(list1)
和行将您的lower_set = set(list2)
列表转换为集合。集合就像一个列表,但没有顺序,并且检查某物是否在集合内比检查它是否在列表中要快得多。由于我们进行了大量此类检查,因此在这里使用集合是正确的数据结构。
其他变化:
f
以只读模式打开并引用输入文件,因此不应写入 - 仅fnw
写入。fnw.close()
不需要,因为该with
语句已经为您做到了。
推荐阅读
- laravel - 为什么 Laravel 显示将我发送到错误的路线?
- vue.js - chart.js 如何为两个轴配置标签
- google-app-engine - GCP 负载均衡器上的 URL 正则表达式映射
- python - 连接列表时int对象不可迭代?
- list - 合并字典列表
- python - 教程 4 中的 Django 教程错误(/polls/1/ 处的操作错误)
- sql-update - 如何使用 Amazon Redshift 中的临时表列更新现有表中的列?
- javascript - 在浮动 div 中设置 CKEditor 5(Vue 组件)的高度
- sql - PostgreSQL - 在 JOIN 条件中不允许使用聚合函数
- php - 查询以显示基于最新日期的最新值