【避免Python循环中的计数器增量】教程文章相关的互联网学习教程文章

python – 创建有序计数器【代码】

我一直在阅读super()的工作原理.我遇到了this recipe,演示了如何创建有序计数器:from collections import Counter, OrderedDictclass OrderedCounter(Counter, OrderedDict):'Counter that remembers the order elements are first seen'def __repr__(self):return '%s(%r)' % (self.__class__.__name__,OrderedDict(self))def __reduce__(self):return self.__class__, (OrderedDict(self),)例如:oc = OrderedCounter('adddddbr...

python – __getattr__的计数器部分【代码】

我试图找到一种方法来设置封装到类中的dict值,例如使用__getattr__我可以返回内部dict值,但是即使属性存在也会调用__setattr__,这使得我的实现很难看.以下示例简化了我的实际类继承自Subject类(观察者模式的主题部分) 我想要实现这样的事情:obj = Example() obj.username = 'spidername' # all OK username is a key in the internal dict # but company is not a key in the internal dict so obj.company = 'ABC' # will raise ...

python – 增加计数器并在超过阈值时触发操作【代码】

我有这样的模特class Thingy(models.Model):# ...failures_count = models.IntegerField()我有需要执行此操作的并发进程(Celery任务): >做某种处理>如果处理失败,则增加相应Thingy的failure_counter>如果failures_counter超过某些Thingy的阈值,则发出警告,但只发出一个警告. 我有一些关于如何在没有竞争条件的情况下执行此操作的想法,例如使用显式锁定(通过select_for_update):@transaction.commit_on_success def report_failur...

python – 使用单例作为计数器【代码】

我有一个自动化测试,它使用为文件夹创建屏幕截图的功能.此功能由多个屏幕截图实例调用.在每次测试运行时,都会创建一个新文件夹,所以我不关心计数器重置.为了反映这些屏幕截图的顺序,我必须提出可以按顺序排序的名称.这是我的解决方案:def make_screenshot_file(file_name):order = Counter().counttest_suites_path = _make_job_directory()return make_writable_file(os.path.join(test_suites_path,'screenshot',file_name % or...

在Python中反复使用计数器创建文件【代码】

基本上我想要做的是编写一个python脚本,用于创建文件名中带有count-number的文件,例如“file 1.txt”“file 2.txt”“file 3.txt”. 我走到这一步:import shutil, os, itertoolsfor i in itertools.count():file = open("FILE " + str(i) + ".txt", 'w+')print(i)time.sleep(1)基本上我能做的就是数数,但文件创建是我的问题. open()似乎不起作用.如何创建这些文件,如何选择directorys来存储文件?解决方法: import shutil, os, it...

python – 我可以将计数器反转到没有倍数的列表列表吗?【代码】

使用Collection Counter,l1 = ['a', 'b', 'b', 'c', 'c', 'b', 'e'] l2 = ['a', 'b', 'b', 'c', 'c', 'b','d']from collections import Counterc1 = Counter(l1) c2 = Counter(l2)# Intersection c1 & c2>>> Counter({'b': 3, 'c': 2, 'a': 1})什么成语可以将Collections Counter分配到列表列表中,每个列表在每个列表中只出现一次?[['a', 'b', 'c'],['b', 'c'],['b']]解决方法:不知道你是否在寻找单线,但这是一个单线: 码:[sor...

python – 处理时的Jupyter笔记本计数器【代码】

我正在使用Jupyter Notebook和Python 3.0. 我有一段代码需要一段时间才能在Jupyter Notebook中执行并确定其当前状态,我想对它的循环进行计数,如下所示:large_number = 1000 for i in range(large_number):print('{} / {} complete.'.format(i,large_number))这个问题是它将为每次迭代打印一个新行,我不想这样做…而只是想更新该值. 无论如何我可以在Jupyter笔记本中做到这一点吗?解决方法:我喜欢制作ascii状态栏.假设你需要运行1...

python – 递归函数中的计数器【代码】

我是python和编程的新手.我编写了一个函数,它将搜索数组中的相邻元素,并寻找值相互之间0.05的值,就像泛光填充算法一样.唯一的区别是我在计算函数运行的时间时做了一些愚蠢的事情(我想这也会告诉我我发现了多少元素),所以我的计数器值是错误的.代码在找到彼此相差0.05的相邻元素时起作用,只是计数很有趣.def floodcount (x,y,array,value,count=0): #akin to a bucket fill in paint, finds the area insteadnrows = len(array)...

计数器的任何漂亮的python字符串格式?【代码】

是否有任何字符串格式用于使用正确的后缀和日志消息,例如:for n in itertools.count():print 'printing for the {:nth} time'.format(n)预期产量:printing for the 0th time printing for the 1st time printing for the 2nd time printing for the 3rd time printing for the 4th time printing for the 5th time ... printing for the 23rd time ... printing for the 42nd time ... etc我可以很容易地自己动手,但我想知道是否...

避免Python循环中的计数器增量【代码】

如何避免在以下Python代码中手动递增序列计数器:sequence = 0 for value in random.sample(range(1000), 7):# do something with value and sequencesequence += 1解决方法:枚举!您可以参考Python docs.for sequence, value in enumerate(random.sample(range(1000), 7)):# do something with value and sequence

python – 使用计数器合并字典【代码】

我有以下词典(示例):>>> x = {'a': 'foo', 'b': 'foobar'} >>> y = {'c': 'barfoo', 'd': 'bar'}我想取每个键的键并使它们成为另一个dict的值,比如z,这样z的键是一个递增的计数器,等于两个序列的长度.>>> z = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}您可以注意到,z的键是递增计数器,值是x和y的键. 我该如何实现这一目标?我尝试了各种解决方案并使用zip,但似乎都没有效果.可能是因为我必须连续更新z字典. 有什么建议?解决方法: In [1]...

有没有办法在Python的for循环中访问迭代计数器?【代码】

有没有办法在Python的for循环中访问迭代计数器? 我通常使用自己的变量并在任何循环中增加它.有更多的pythonic方式吗?解决方法:使用enumerate:sequence = [1, 45, 65, 7] for i, val in enumerate(sequence):print i, val输出:0 1 1 45 2 65 3 7

python – django模板中的自定义计数器【代码】

我在django模板页面中有这个代码<select class="selectpicker datatable-column-control" multiple {% for q_group in question_groups %}<optgroup label="{{ q_group.name }}">{% for q in q_group.questions %}<option value="{{ forloop.counter0 }}">{{ q.title }}</option>{% endfor %}</optgroup> {% endfor %}我希望每个迭代中增加的每个选项标记都有一个值.如果我有10个选项标签,那么它们的值将从0到9.forloop.counter0不...

python – App Engine分片计数器和高复制数据存储区【代码】

我正在使用App Engine和最终一致的高复制数据存储.我也在使用分片计数器. 当我查询所有分片并总结它们时,我能否认为计数是一致的?也就是说,下面的代码会返回我的分片计数的准确总和吗?sum = 0 for counter in Counter.all():sum += counter.count解决方法:如果要创建强一致的分片计数器,则应使用键,而不是查询.#for getting total = 0 shard_keys = [] for i in range(20): #20 shardskey_name = shard + str(i)shard_keys.appen...

比较Python中的计数器列表【代码】

我在python中有一个计数器列表:[Counter({12.011: 30.0, 15.999: 2.0}), Counter({12.011: 12.0, 15.999: 2.0}),... Counter({12.011: 40.0, 15.999: 5.0, 79.904: 5.0})]如何查找每个Counter元素的计数.计数器给我一个不可用类型的错误.我想的另一种方法是在嵌套的for循环中遍历列表,检查每个计数器是否等于列表中的任何其他计数器并相应地增加字典.有更好的解决方案吗?解决方法:您可以将每个Counter转换为key,value(items)元组...