(If String in Variable)语句没有过滤掉数据

(If String in Variable) statement is not filtering out data

试图过滤掉字符串中没有 'PC' 的数据,但它似乎没有捕获到任何东西,只是转到了 else。不确定 csvRow 是否甚至是一个字符串,也许这就是它不起作用的原因,但我刚开始 Python 并且不知道如何解释它。

csvRow 返回的示例数据:

['0', '0', '30', 'Testing Unit', 'True', 'COMP_PC', 'COMP_PC']
['0', '0', '30', 'Prod Unit', 'True', 'ASSM_UL', 'ASSM_UL']

代码:

for csvRow in reader(csvRows[2:]):

    if "PC" in csvRow: 
        for csvValue in csvRow:
            values += csvValue + "\t"
        values = values[:-1] + "\r\n"
    else:
        continue

编辑:

为此拼凑了一个解决方案,但我不确定它是否有效。 有什么建议吗?

for csvRow in reader(csvRows[2:]):
    for csvValue in csvRow:
        if "PC" in csvValue: 
            for csvValue2 in csvRow:
                values += csvValue2 + "\t"
            values = values[:-1] + "\r\n"
            break
        else:
            continue

想通了,正如 furas 所说:

"PC" in string can check if "PC" is part of longer string. "PC" in list checks if there is exact string "PC" in list - but it can't check if "PC" is part of longer string in this list.`

只需遍历列表并检查那里。

for csvRow in reader(csvRows[2:]):
    for csvValue in csvRow:
        if "PC" in csvValue: 
            for csvValue2 in csvRow:
                values += csvValue2 + "\t"
            values = values[:-1] + "\r\n"
            break
        else:
            continue

即使您想使用其他分隔符(即 \t 而不是 ,),使用 the csv module 仍然是个好主意。它将更好地生成格式正确的输出。

这是一个例子:

import csv
import io

# Representing csvRows as a 2D array, hopefully approximating your input.
csvRows = [
    ['0', '0', '30', 'Testing Unit', 'True', 'COMP_PC', 'COMP_PC'],
    ['0', '0', '30', 'Prod Unit', 'True', 'ASSM_UL', 'ASSM_UL'],
]

# Using a StringIO instance to capture the output, alternatively you
# can easily write to a file.
results = io.StringIO()
writer = csv.writer(results, delimiter='\t')

# Process your data.
for row in csvRows:
    if any('PC' in value for value in row):
        writer.writerow(row)

# Print the results.
output = results.getvalue()
print(output)

# Use repr() to verify that each line is terminated with '\r\n'.
print(repr(output))

输出:

$ python3 example.py
0       0       30      Testing Unit    True    COMP_PC COMP_PC

'0\t0\t30\tTesting Unit\tTrue\tCOMP_PC\tCOMP_PC\r\n'