(若变量中有字符串)语句未筛选出数据

2024-10-04 17:15:51 发布

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

试图筛选出字符串中没有“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

Tags: 数据字符串intrueforunitulelse
2条回答

正如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 ^{} 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'

相关问题 更多 >

    热门问题