Python 将除一个变量外的所有变量设置为false
我正在读取一些文本文件,并使用flag将数据附加到相应的变量中。 案文如下:Python 将除一个变量外的所有变量设置为false,python,Python,我正在读取一些文本文件,并使用flag将数据附加到相应的变量中。 案文如下: header_1 some text ------------ ----------- some text header_2 some text ------------ ----------- some text header_3 some text ------------ ----------- some text 我正在逐行阅读,所以: if line=='header_1':
header_1
some text
------------
-----------
some text
header_2
some text
------------
-----------
some text
header_3
some text
------------
-----------
some text
我正在逐行阅读,所以:
if line=='header_1':
flag_1 = True
if line=='header_1':
flag_1 = False
flag_2 = True
if flag_1:
data_1.append(line)
elif flag_2:
data_2.append(line)
我要避免的是,每次我进入文件的下一部分时,再次将“上一个标志”设置为false,或者以更有效的方式进行设置。与其将所有内容硬编码为单独命名的变量,不如使用更广泛的条件并将数据存储在数据结构中:
result = []
for line in file:
if line.startswith('header_'):
result.append([])
else:
result[-1].append(line)
这将遍历文件以查找标题。无论何时,只要找到一个,它就会将一个新列表添加到您的总体结果中。否则,它会将该行添加到最后一个可用的列表中。构建一个字典,标题作为键,相应的数据列表作为值。将最后一个有效标头保留在内存中。因此:
dict_of_results = {}
curr_header = ""
for line in file:
if line.startswith('header_'):
curr_header = line
if curr_header not in dict_of_results:
dict_of_results[curr_header] = []
dict_of_results[curr_header].append(line)
此表单还允许相同的标题在文本中的不同位置出现。使用索引而不是标志如何?假设你有两种内容
toAppend = [[], []]
flag = 0
for line in f:
if line =='header_1':
flag = 1
elif line == 'header_2':
flag = 2
if flag:
toAppend[flag - 1].append(line)
为什么不用一个
state
变量替换这些标志呢
skip, h1, h2 = range(3)
state = skip
for line in lines:
if line == 'header_1':
state = h1
continue
elif line == 'header_2':
state = h2
continue
if state == h1:
data_1.append(line) # or whatever
elif state == h2:
data_2.append(line)
这是一种非常灵活的方法:如果标志不是互斥的,您可以使用一组标志:
h4, h5 = range(4, 6)
for line in lines:
if line == 'header_45':
state == {h4, h5}
continue
if state == {h5, h4}:
do_smth()
if h5 in state:
do_smth_more()
如果当前标题不在结果目录中,您可以通过
dict.get(键,默认值)
或使用defaultdict
替换,但不确定问题是否与“标题”+数字有关。没有模式的头怎么样?@Musen-没有模式的程序是不可能存在的,而且创建这样的头也没有多大意义。此外,问题中的代码具有带有模式的标题。