list. append()似乎重写了list中的值



我正在导入一个CSV文件,其中有三个商店(商店a, B和C),有商品的行,并且在行的单元格中有值,表示该商店是否销售该商品。

我试图遍历每一行,我的目标是找到只在一个商店出售的物品(该商店唯一的物品)

如果商店有唯一的商品,我想将该商品附加到列表中(每个商店都有一个)。

我的问题是,当我打印所有的项目与我的条件,它显示我所有的项目是唯一的商店,然而,当我将它们附加到我的列表并打印我的列表,只有最后一个项目显示(这就是为什么我认为它被覆盖)。

import csv
reader = csv.DictReader(open("storeLists.csv"))
for row in reader:
STORES = [row]
"COMPARING ALL THE SHOPS TO GATHER ALL THE UNIQUE ITEMS OF EACH SHOP AND SAVE THE INTO A LIST"
if row["STORE A"] == "Y" and row["STORE B"] != "Y" and row["STORE C"] != "Y":
storeAuniqueItems = []
storeAuniqueItems.append(row["NAME"])

elif row["STORE A"] != "Y" and row["STORE B"] == "Y" and row["STORE C"] != "Y":
storeBuniqueItems = []
storeBuniqueItems.append(row["NAME"])

elif row["STORE A"] != "Y" and row["STORE B"] != "Y" and row["STORE C"] == "Y":
storeCuniqueItems = []
storeCuniqueItems.append(row["NAME"])

else:
print("NaN")
print("STORE A:", storeAuniqueItems)
print("STORE B:", storeBuniqueItems)
print("STORE C:", storeCuniqueItems)

您在每次迭代中创建一个新的列表,这导致了问题。

尝试以下操作:

import csv
reader = csv.DictReader(open("storeLists.csv"))
storeAuniqueItems = []
storeBuniqueItems = []
storeCuniqueItems = []
for row in reader:
STORES = [row]
"COMPARING ALL THE SHOPS TO GATHER ALL THE UNIQUE ITEMS OF EACH SHOP AND SAVE THE INTO A LIST"
if row["STORE A"] == "Y" and row["STORE B"] != "Y" and row["STORE C"] != "Y":
storeAuniqueItems.append(row["NAME"])

elif row["STORE A"] != "Y" and row["STORE B"] == "Y" and row["STORE C"] != "Y":
storeBuniqueItems.append(row["NAME"])

elif row["STORE A"] != "Y" and row["STORE B"] != "Y" and row["STORE C"] == "Y":
storeCuniqueItems.append(row["NAME"])

else:
print("NaN")
print("STORE A:", storeAuniqueItems)
print("STORE B:", storeBuniqueItems)
print("STORE C:", storeCuniqueItems)

相关内容

  • 没有找到相关文章

最新更新