我正在尝试将列表作为参数传递给函数,如果该函数在提供的列表中包含字符串,则它将从csv抓取一行。我无法更改itemA的索引。它只打印列表的最后一项!
GAS=[
"SUNOCO",
"CUMBERLAND",
"MOBIL"]
gasLength=len(GAS)
print(gasLength)
def parseData(csvToParse = transactionsCSV, itemA="", itemB=""):
#For Loop to append to CSV
for row in csvToParse:
if itemA in row[3]:
csv_personA.writerow([row[0],row[1],row[2],row[3],row[4],row[5]])
print(row[3])
print(itemA)
elif itemB in row[3]:
csv_personB.writerow([row[0],row[1],row[2],row[3],row[4],row[5]])
#This Was suggested but still only returns the GAS index of 0
for counter, _ in enumerate(range(gasLength)):
parseData(csvToParse=transactionsCSV, itemA=GAS[counter], itemB="")
for _ in range(gasLength):
x = gasLength-1
parseData(csvToParse=transactionsCSV, itemA=GAS[x], itemB="")
# My first attempt is below!!!
#Get gas purchases
def parseGasStations():
x = 0
itemsToCheck = row_count*gasLength
print(itemsToCheck)
#while x is less than total of items in the main csv times the number of items in the gas array.
while x < itemsToCheck:
a = 0
y = 0
#While a is less than the total number of rows in the main
while a < row_count:
print(GAS[y])
for _ in range(gasLength):
parseData(csvToParse=transactionsCSV, itemA=GAS[gasLength-1], itemB="")
if y != gasLength-1:
y += 1
elif y == gasLength-1:
y = 0
a += 1
x += 1
parseGasStations()
输出仅将MOBIL工作站附加到CSV,而不像我认为的那样在列表中建立索引。
答案 0 :(得分:0)
因此,如果要在迭代中使用数字迭代计数器,则可以执行以下操作。
for counter, _ in enumerate(range(gasLength)):
parseData(csvToParse=transactionsCSV, itemA=GAS[counter], itemB="")
Enumerate返回一个包含计数器和元素本身的元组。
答案 1 :(得分:0)
感谢Fluxens,我能够弄清楚这一点! 这是一个将列表作为参数并在所有项目之间建立索引的函数!
GAS=(
"SUNOCO",
"CUMBERLAND",
"MOBIL",
"BESTWAY",
"AMORE FUEL")
gasLength=len(GAS)
def parseData(csvToParse="", catagory=(), catagorySize=""):
#For loop to check each row in master csv
for row in csvToParse:
#For loop to index through catagory items to look for in each row
for counter, _ in enumerate(range(catagorySize)):
if catagory[counter] in row[3]:
csv_mark.writerow([row[0],row[1],row[2],row[3],row[4],row[5]])
print(row[3])
print(catagory)
parseData(csvToParse = transactionsCSV, catagory=GAS, catagorySize=gasLength)