尝试使数组遍历Excel文件的每一行

时间:2018-08-29 15:12:56

标签: python arrays excel python-3.x loops

我正在尝试遍历Excel文件的每一行以及数组中的每个值。我想要第一个匹配项打印“找到数组值”,如果找不到匹配项,我想打印“找不到数组值”

如果除我想找到匹配项而跳出循环之外,否则大多数情况下都可行。

使用lxrd

for row_num in range(sheet.nrows):
    for n in name_array:
        row_vlaue = sheet.row_values(row_num)
        if row_vlaue[4] == r in name_array:
            print(n, "found")
            break
        else:
            print(n, "not found")

1 个答案:

答案 0 :(得分:0)

从您的代码看来,您似乎仅在第5个单元格(row_vlaue[4])上搜索值,如果是这样,那么这应该足够了:

for row_num in range(sheet.nrows):
    row_vlaue = sheet.row_values(row_num)
    if row_vlaue[4] in name_array: # this checks if the 5th cell is in your list of searched values
        print(row_vlaue[4], "found on row", row_num)
        name_array.remove(row_vlaue[4]) # we remove the element we've found
        if not name_array: # nothing else to search for
            print("found them all")
            break
else:
    # this else will be executed only if the break was not called
    # this means that there still something left in in list of searched values
    print(name_array, "not found") 

稍后编辑:更改了答案以获取所有搜索到的值