Python印的线太多了,我只想印上

2024-10-04 03:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信这个问题在这里已经讨论过很多次了,我只是找不到合适的词来找到与这个问题相关的问题。在

这是我的密码。在

def getcopies(listoflists, id_col):
    for item in listoflists[1:]:
        key = getid(item[id_col])
        copies[key] = copies.get(key, 0) + 1
        print copies

这是我的输出。在

^{pr2}$

这就是我想要的输出。在

{'20302001': 1, '20301001': 1, '20300001': 1, '20303001': 1}

我的代码显然运行缓慢。如何使其更快,如何避免不需要的输出?在


Tags: keyinid密码forgetdefcol
3条回答

将您的print copies放在循环之外,并在启动循环之前初始化它。在

   copies = {}
   for item in listoflists[1:]:
        key = getid(item[id_col])
        copies[key] = copies.get(key, 0) + 1
   print copies

找到了!对不起,我应该把我所有的代码都贴出来。问题出在getid()上。我是这样定义的:

def getid(rough_id):
    if len(rough_id)>=8:
        i = 0
        while i <= len(rough_id) - 8:
            if rough_id[i:i+8].isdigit():
                id = rough_id[i:i+8]
                break
            else:
                i += 1
    else:
        print "rough_id is too short"
    return id

当我把它改成:

^{pr2}$

一切都开始奏效了。在

只需删除最后一行的缩进。“for item”下面缩进的所有内容都将执行x次,其中x是任何元素中的元素数。在

def getcopies(listoflists, id_col):
    for item in listoflists[1:]:
        key = getid(item[id_col])
        copies[key] = copies.get(key, 0) + 1
    print copies

相关问题 更多 >