【问题标题】:Python script struck while creating dictionary as for each key of dictionary , there are multiple values( 300 entries) listPython脚本在创建字典时为字典的每个键敲击,有多个值(300个条目)列表
【发布时间】:2012-08-09 17:17:15
【问题描述】:

我是初学者。我编写了一个脚本,它接受 1000 万个条目的输入列表(以 a:b 的形式,其中 a 和 b 是字母数字)。

现在我想根据这些条目创建一个字典。对于许多列表条目,第二部分(冒号之后)很常见。 (例如 a:b、f:b、k:b——在这种情况下,我的键是 b,值是列表 [a,f,k])。

但不知何故,我的剧本被击中了。我可以从日志中看到脚本被触发并且日志大小没有增加。 (对于我字典的每个键,都有一个大小在 400 到 500 之间的列表。这可能是个问题吗?)

如果我的输入列表包含的条目较少,我的脚本就可以正常工作。

列表名称匹配

print 'match2 list: %s' % match2 # it shows the 10 million entries in form of a:b as expected 
for i in xrange(len(match2)):
    print 'Before Splitted variable : %s' % match2[i] # this print is for information
    templist = re.split(':', '%s' % match2[i])
    print 'Splitted list : %s' % templist # this print is for information
    length3 = len(templist)
    print "Length3 :%d" %length3
    key1 = templist[1]
    value1 = templist[0]
    if example.has_key(key1):
       example[key1].append(value1)
    else:
       example[key1] = value1

请提出您的建议。

【问题讨论】:

  • 这段代码看起来不错。 . .有点丑陋和低效,但很好;)我会添加一些东西来打印出 i,并检查它是否总是在同一点失败 - 可能是您的输入数据或某些周围逻辑的问题。
  • 这与您所问的问题无关,但我认为re.split 在这里有点矫枉过正。你可以只做templist = match2[i].split(':', maxsplit=1),这将有一个额外的好处是保证len(templist) == 2,因为最多分裂一次。
  • 如果您知道您的列表条目中始终包含: 并执行value1, key1 = match2[i].split(':', maxsplit=1),您甚至可以更进一步。

标签: python dictionary python-3.x


【解决方案1】:

我怀疑问题出在这里:

if example.has_key(key1):
   example[key1].append(value1)
else:
   example[key1] = value1

example 不包含key1 时,它会为其创建一个新条目,其值为字符串value1。如果示例确实包含key1,它会尝试将字符串value1 附加到已经存在的任何内容上。但是,这没有任何意义。您不能使用append 附加两个字符串。

你可能想要:

if example.has_key(key1):
   example[key1].append(value1)
else:
   example[key1] = [value1] #the value is a list containing one string

【讨论】:

  • 不错,但这不应该抛出 AttributeError 并退出吗?
  • 是的,这就是我测试代码时发生的情况。我怀疑 OP 在更高的地方有一个 try-catch,它正在默默地吃掉错误。
  • 如果它之前有一个try: except:,它不是立即退出循环还是继续循环,而不是冻结?
猜你喜欢
  • 1970-01-01
  • 2021-12-17
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2022-06-27
  • 1970-01-01
相关资源
最近更新 更多