【问题标题】:if loop does not end after returnif循环在返回后没有结束
【发布时间】: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


【解决方案1】:

我无法让你的代码运行,实现你想要的,试试这个:

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"

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2018-07-01
    • 2012-10-04
    相关资源
    最近更新 更多