我有以下代码:
with open(s+ ".csv", mode='r') as f:
reader = csv.reader(f)
for row in reader:
for gtin,currentstock in dictionary.items():
#if row[0] in the file is equal to the key value in the dictionary...
if row[0]==gtin:
#Print the row for reference and...
print(row)
#Create a new list that would store the output (that is several rows)
newdetails=[]
line=row
newdetails.append(line)
#print all the rows (as a list of lists?) that are produced by the loop
print("This prints only the last line...why?")
print(newdetails)
输入为GTIN:12121212和GTIN 12345670(这些是存储在字典中的两个GTIN,我想在文件中查找)。
接下来我需要做两件事,非常感谢一些帮助。
输出如下:
Want to update stock levels based on last order? - y/)y
and here is my latest attempt.....
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
This prints only the last line...why?
[['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
根据建议,我已经将newline = []排除在循环之外。但现在它做了更奇特的事情。它只打印文件中的最后一行(它不符合循环中设置的条件!)。
with open(s+ ".csv", mode='r') as f:
reader = csv.reader(f)
for row in reader:
for gtin,currentstock in dictionary.items():
#if row[0] in the file is equal to the key value in the dictionary...
if row[0]==gtin:
#Print the row for reference and...
print(row)
#Create a new list that would store the output (that is several rows)
newdetails=[]
line=row
newdetails.append(line)
使用了相同的输入(首先打印的两个GTIN编号 - 这样位工作)。它创建了一个我需要帮助的新列表/答案。任何人吗?
以下(更改后)的输出:
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
#This is now printing the last record in the FILE.
[['9876545', 'Acer Allinone', '550', '5', '3', '5']]
我想要的是以某种格式存储前两行(与字典中的GTIN号匹配)(列表,我猜是吗?)。
谢谢你Jeon - 根据你的建议,我修改了代码并且它的工作原理 - 很近!!!
现在的代码是:
with open(s+ ".csv", mode='r') as f:
newdetails=[]
reader = csv.reader(f)
for row in reader:
for gtin,currentstock in dictionary.items():
#if row[0] in the file is equal to the key value in the dictionary...
if row[0]==gtin:
#Print the row for reference and...
print(row)
#Create a new list that would store the output (that is several rows)
line=row
newdetails.append(line)
#print all the rows (as a list of lists?) that are produced by the loop
print("?!?!?!??!?!")
print(newdetails)
输出是仁慈的,我有点期待它:
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
?!?!?!??!?!
[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
所以,现在我在列表中有一个列表。我真的很感激一些指导是如何通过查找字典中的值来替换这个列表列表(newdetails)。例如,
pseudocode:
if GTIN no matches index of list1 (in newdetails)
for that particular list(row), update the value of current stock, with the
corresponding VALUE for the KEY(GTIN) in dictionary.
任何? ....