Python 如果循环在返回后未结束
各位委员: 我已经绞尽脑汁好几个小时了,为什么我的代码不起作用 我从CSV文件中获取数据,当两个代码匹配时,我尝试更改一个值Python 如果循环在返回后未结束,python,loops,if-statement,Python,Loops,If Statement,各位委员: 我已经绞尽脑汁好几个小时了,为什么我的代码不起作用 我从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:
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
条形码_至_match.txt:
BLA00BLA00
BLI00BLI00
因此,我需要将Product rowsBLA00BLA00和BLI00BLI00 Published列的值更改为False
有人可以检查我的方法来替换这些值吗
谢谢
编辑:
当我添加print命令时,代码似乎在无限循环的最后一次匹配中存储
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
我无法运行您的代码,要实现您想要的,请尝试以下操作:
import csv
import pandas as pd
data_df = pd.read_csv('Products.csv')
print(data_df)
with open("Barcodes_to_match.txt") as f:
barcodes = f.read().splitlines()
data_df.loc[data_df['Bar_Code'].isin(barcodes), 'Published'] = False
print(data_df)
data_df.to_csv(('Products.csv'), encoding='UTF-8', quoting=csv.QUOTE_ALL, quotechar='"', index=None, sep=str(","))
Products.csv
"Bar_Code","Product","Published"
"BLA00BLA00","Product1","False"
"BLU00BLU00","Product2","False"
"BLI00BLI00","Product3","False"
"BLE00BLE00","Product4","False"
如果返回后循环未结束?这是一个矛盾。返回退出函数;此后循环将无法再运行。请参阅有关函数的任何教程。如果您需要更多帮助,请提供一个。该代码应该做什么?