【发布时间】:2019-09-17 01:52:11
【问题描述】:
我想知道如何使变量与另一个变量一起相应地更改:
with open(csv_file, 'r', newline='') as csvfile:
counter = csv.reader(csvfile, dialect='myDialect')
counter = islice(counter, startatline, None)
totalpendingtosend = sum(1 for row in counter if 'pending' in row)
csvfile.close()
with open(csv_file, 'r', newline='') as csvfile:
counter = csv.reader(csvfile, dialect='myDialect')
counter = islice(counter, startatline, None)
totalconfirmedtosend = sum(1 for row in counter if 'confirmed' in row)
csvfile.close()
totaltosend = totalpendingtosend + totalconfirmedtosend
在这个示例中,我使用了两次相同的代码,因为 totalpendingtosend 和 totalconfirmedtosend 是硬编码的,但是有没有办法通过使用以下行:
statuses = ['confirmed', 'pending']
for i in statuses:
with open(csv_file, 'r', newline='') as csvfile:
counter = csv.reader(csvfile, dialect='myDialect')
counter = islice(counter, startatline, None)
total_?[i]?_tosend = sum(1 for row in counter if i in row)
csvfile.close()
totaltosend += total_?[i]?_tosend
我也可以以某种方式将通用硬编码变量更改为顶部列表中所写的内容?所以改变这个: ?[i]? 基本上相应地。有没有一种好方法可以做到这一点,以便我稍后也可以在我的代码中读出 totalpendingtosend 和 totalconfirmedtosend ?
提前感谢您的宝贵时间。
【问题讨论】:
-
旁注:当您在
with块(上下文管理器)中打开文件时,之后无需close()。with open(...) as的全部意义在于最后自动清理。 -
任何时候您想开始动态命名变量,请改用
dict。从total_items_to_send = {}开始,在你的 ???线路使用total_items_to_send[i]。或者,使用函数对代码进行重复数据删除:total_pending_to_send = how_many_to_send('pending', startatline); total_confirmed_to_send = how_many_to_send('confirmed', startatline) -
上面的好建议。您可能还想交换
with和for以避免重复文件两次。更极端的建议是使用熊猫,那么整个例子就是一个班轮。 -
谢谢@Amadan。我还没有真正体验过字典的全部潜力,所以我使用了一个简单的列表,其中包含一个 for 循环和条件语句来更改所需的变量。
-
@Marat,我真的不明白你交换
for和with的意思,以及它在更改我的代码时的作用。我已经更新了我使用的解决方案,其中还包含for和with语句。如果您有时间指出迭代问题是否仍然存在,我会很高兴。提前致谢。