一般的编程新手。这是我的代码
for b in range(LengthSpread):
Strip = ReadSpread[b].rstrip('\n')
SplitData = ReadSpread[b].split(",")
PlotID = SplitData[1]
PlotIDnum = float(PlotID)
if PlotIDnum == 1:
List = SplitData
print List
OpenBlank.writelines('%s\n\n\n\n\n' % List)
最终,我想基于更改整个数据集中的每个plotIDnum来查找数据。如何在不实际更改数字的情况下更改条件if语句中的数字。可能使用for循环或while循环。无法绕过它。
这是inputdata的一个例子
09Tree #PlotID PlotID
1 1 Tree
2 1 Tree
3 2 Tree
4 2 Tree
6 4 Tree
7 5 Tree
8 5 Tree
9 5 Tree
我希望我的输出由plotID#组织,并将每个输出放在一个新的电子表格中,或者将每个唯一的数据集放在一个新标签中
感谢您的帮助
答案 0 :(得分:1)
我不确定您希望如何组织文件,但也许您可以使用绘图ID作为文件名(或选项卡的名称或其他)的一部分。这样你甚至不需要额外的循环,例如:
for b in range(length_spread):
data = read_spread[b].rstrip('\n')
splitted = data.split(',')
plot_id = splitted[1] # Can keep it as a string
filename = 'plot_id_' + plot_id + '.file_extension'
spreadsheet = some_open_method(filename, option='append')
spreadsheet.writelines('%s\n\n\n\n\n' % splitted)
spreadsheet.close_method()
也许您也可以使用with
声明:
with some_open_method(filename) as spreadsheet:
spreadsheet.writelines('%s\n\n\n\n\n' % splitted)
这确保(如果你的文件对象支持这个)文件正确关闭,即使你的程序在写入文件时遇到异常。
如果你想使用某种额外的循环,我认为这是最简单的情况,假设你事先知道了所有的情节ID:
all_ids = [1, 2, 4, 5]
# Note: using plot_id as integer now
for plot_id in all_ids:
filename = 'plot_id_%i.file_extension' % plot_id
spreadsheet = some_open_method(filename, option='write')
for b in range(length_spread):
data = read_spread[b].rstrip('\n')
splitted = data.split(',')
if plot_id == int(splitted[1]):
spreadsheet.writelines('%s\n\n\n\n\n' % splitted)
spreadsheet.close_method()