用于删除收入属性列中收入为零的关键字数据行的Python循环
我使用了一个类似的循环来删除重复项,并尝试稍微修改它,以便删除“lastClickRevenue”列中包含值为“0”的整行 代码执行时没有抛出任何错误,但它没有像我希望的那样删除行。任何帮助都将不胜感激用于删除收入属性列中收入为零的关键字数据行的Python循环,python,Python,我使用了一个类似的循环来删除重复项,并尝试稍微修改它,以便删除“lastClickRevenue”列中包含值为“0”的整行 代码执行时没有抛出任何错误,但它没有像我希望的那样删除行。任何帮助都将不胜感激 for i in range(len(lastClickRevenue)): if lastClickRevenue[i] == "0": currentRevenueKeywords.pop(i)
for i in range(len(lastClickRevenue)):
if lastClickRevenue[i] == "0":
currentRevenueKeywords.pop(i)
sessions.pop(i)
sales.pop(i)
lastClickRevenue.pop(i)
firstClickRevenue.pop(i)
我猜数组中存储的值是实际的数字而不是字符串。尝试更改代码以检查数字0而不是字符串“0” 我还建议查看filter函数,以便只保留满足特定条件的值
for i in range(len(lastClickRevenue)):
if lastClickRevenue[i] == 0:
currentRevenueKeywords.pop(i)
sessions.pop(i)
sales.pop(i)
lastClickRevenue.pop(i)
firstClickRevenue.pop(i)
在容器上迭代并同时修改它总是一个坏主意 最好用这样的列表来写:
lastClickRevenue = [x for x in lastClickRevenue if x != 0]
要处理其他问题:
currentRevenueKeywords = [x for x,y in zip(currentRevenueKeywords, lastClickRevenue) if y != 0]
sessions = [x for x,y in zip(sessions, lastClickRevenue) if y != 0]
sales = [x for x,y in zip(sales, lastClickRevenue) if y != 0]
firstClickRevenue = [x for x,y in zip(sales, lastClickRevenue) if y != 0]
lastClickRevenue = [x for x in lastClickRevenue if x != 0]
或者,您可以通过一次完成所有这些操作,使其更具吸引力:
currentRevenueKeywords, sessions, sales, firstClickRevenue, lastClickRevenue = zip(*[(a,b,c,d,x) for (a,b,c,d,x) in zip(currentRevenueKeywords, sessions, sales, firstClickRevenue, lastClickRevenue) if x != 0])
我应该提到的是:看起来您可能会受益于以某种表格格式或字典存储数据,而不是一堆列表 谢谢你,泰勒。我会用这种方法转一转谢谢wim。这些建议很有道理。将致力于合并。