迭代循环以更改条件语句python

2024-06-26 13:37:21 发布

您现在位置:Python中文网/ 问答频道 /正文

一般编程新手。这是我的密码

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的一个示例

^{pr2}$

我希望输出按plotID#组织,并将每个输出放入新的电子表格或在新的选项卡中包含每个唯一的数据集

谢谢你的帮助


Tags: 数据in密码forif编程range数字
1条回答
网友
1楼 · 发布于 2024-06-26 13:37:21

我不确定您希望如何组织您的文件,但也许您可以将plot 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语句:

^{pr2}$

这可以确保(如果文件对象支持此功能),即使程序在写入文件时遇到异常,文件也会正确关闭。在

如果你想使用某种额外的循环,我认为这是最简单的情况,假设你事先知道所有的绘图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()

相关问题 更多 >