在Python中,如何迭代循环中的多个变量?

2024-06-26 02:10:30 发布

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

我有一个Python脚本,它读取一个.xls文件,并使用循环删除每行中所有不必要的返回。到目前为止,我的脚本可以遍历我指定的行并删除返回,但是我希望它自动遍历每一行并删除所有不必要的返回。这是我的剧本-


import xlrd
import xlwt

# function for removing returns in file
edits_returns = ''
def remove_returns1(row, column):
    global edits_returns
    cell_hold = sheet.cell(row, column).value
    cell_hold_str = str(cell_hold)
    if "\n" in cell_hold_str:
        edits_returns = edits_returns + ('Return(s) replaced in (row %d : cell %d.)\n' % (row, column))
    out_cell = cell_hold_str.replace('\n', '')
    return out_cell

# obtaining filename
fname = raw_input('Input Filename > ')

# opening file
workbook = xlrd.open_workbook(fname)
sheet = workbook.sheet_by_index(0)

# informing user of # of rows and columns
print "\nNumber of rows: %d" % sheet.nrows
print "Number of Columns: %d\n" % sheet.ncols

# removing returns by row
column = 0
while column < sheet.ncols:
    new_value = remove_returns1(34, column)
    column += 1
    print new_value,

# printing the edits
print "\n\n", edits_returns

  • 我的问题

    1. 如何自动而不是手动遍历每一行?你知道吗
    2. 有没有更好的方法来打印编辑结果,如edit_results所示?(我计划让这个脚本在将来做的不仅仅是删除退货)
    3. 我是在做一些多余的事情,还是我在脚本中写的东西可以做得不同?你知道吗

输入示例:

10/13/15 mcdonalds\n $20 0.01%
10/13/15 mcdonalds\n $20 0.01%

输出示例:

10/13/15 mcdonalds $20 0.01%
10/13/15 mcdonalds $20 0.01%
  • 所有的行仍在各自的行上。它们没有连接。你知道吗

所提供答案之一的输出示例:

10/13/15 mcdonalds $20 0.01%10/13/15 mcdonalds $20 0.01%

这看起来很接近,但仍然不是我要找的。你知道吗


提前谢谢!我愿意接受所有建设性的批评。你知道吗


Tags: ofin脚本valuecellcolumnreturnssheet
1条回答
网友
1楼 · 发布于 2024-06-26 02:10:30

替换

# removing returns by row
column = 0
while column < sheet.ncols:
    new_value = remove_returns1(34, column)
    column += 1
    print new_value,

# printing the edits
print "\n\n", edits_returns

在下面。你需要一行一行地检查,然后再检查每一列。你知道吗

# removing returns by row
row_idx =0
while row_idx < sheet.nrows:
    col_idx = 0
    while col_idx < sheet.ncols:
        new_value = remove_returns1(row_idx, col_idx)
        col_idx += 1
        print new_value,

    print      
    row_idx += 1

要将每一行存储到一个变量中,首先需要将这些列附加到一个列表中,然后将它们连接起来。你知道吗

row_idx =0
while row_idx < sheet.nrows:
    col_idx = 0
    row_data =[]
    while col_idx < sheet.ncols:
        new_value = remove_returns1(row_idx, col_idx)
        col_idx += 1
        row_data.append(new_value)

    a= ' '.join(row_data)
    print a
    row_idx += 1

如果不想立即打印或使用,也可以将“a”列为一个列表并将所有行追加到其中。你知道吗

相关问题 更多 >