【发布时间】:2020-03-18 01:27:01
【问题描述】:
会员,
我好几个小时都在头疼,为什么我的代码不起作用。
我正在从 CSV 文件中获取数据,并且当两个代码匹配时,我正在尝试更改一个值。
def mode(x):
for line in data_df['Bar_Code']:
#print(line) ~ Line outputs the Barcodes in the Bar_Code Column of the CSV file.
with open("Barcodes_to_match.txt") as barcodes:
for barcode in barcodes:
#print(barcode) ~ Outputs the Barcode that it need to be matched.
if barcode == line:
x = x.replace("True", "False")
return x
data_df['Published'] = data_df['Published'].apply(lambda x: mode(x))
data_df.to_csv(('Products.csv'), encoding='UTF-8', quoting=csv.QUOTE_ALL, quotechar='"', index=None, sep=str(","))
Product.csv 文件:
Bar_Code, Product, Published
BLA00BLA00, Product1, True
BLU00BLU00, Product2, False
BLI00BLI00, Product3, True
BLE00BLE00, Product4, False
Barcodes_to_match.txt:
BLA00BLA00
BLI00BLI00
所以,我需要将 Product 行(BLA00BLA00 和 BLI00BLI00)Published 列的值更改为 False
有人可以检查我替换值的方法吗?
谢谢!
编辑: 当我添加打印命令时,代码似乎在无限循环的最后一场比赛中储存。
if barcode == line:
print(barcode + " = " + line)
x = x.replace("True", "False")
return x
Output:
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
【问题讨论】:
-
"如果循环在
return之后没有结束"?这是一个矛盾。return退出函数;之后循环不能再运行了。请参阅任何有关函数的教程。 -
如果您需要更多帮助,请提供minimal, reproducible example。
-
这段代码应该做什么?
标签: python loops if-statement