2 回答

TA貢獻1784條經驗 獲得超7個贊
根據 Niels 的說法,我會更改 2 循環并遍歷行本身并檢查當前行條目是否在“壞”列表中:
for row in filereader:
for s in row:
if s not in stringlist:
data1 = row[0]
而且我也不知道您想對 data1 做什么,但是當項目不在 stringList 中時,您總是會更改對象引用。您可以使用列表將項目添加到列表中data1.append(item)

TA貢獻1776條經驗 獲得超12個贊
你可以嘗試這樣的事情。
stringList = [] #strings look like "AAA", "AAB", "AAC", etc.
with open('BadStrings.csv', 'r')as csvfile:
filereader = csv.reader(csvfile, delimiter=',')
for row in filereader:
stringToExclude = row[0]
stringList.append(stringToExclude)
data1 = [] # Right now you are overwriting your data1 every time. I don't know what you want to do with it, but you could for exmaple add all row[1] to a list data1
with open('OtherData.csv', 'r')as csvfile:
filereader = csv.reader(csvfile, delimiter=',')
next(filereader, None) #Skip header row
for row in filereader:
found_s = False
for s in stringList:
if s in row:
found_s = True
break
if not found_s:
data1.append(row[1]) # Add row[1] to the list is no element of stringList is found in row.
仍然可能不是一個巨大的性能改進,但至少 for 循環for s in stringList:現在會在找到 s 后停止。
添加回答
舉報