【发布时间】: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