编辑:添加更多信息
如何将新列表“附加”到已经压缩的列表中。这样做的主要原因是,我需要在字典中扫描并拆分任何具有特定字符的字段,并将结果列表添加到ziplist中。
dictionary = {
'key1': 'testing'
'key2': 'testing'
'key3': '6-7-8',
}
list1 = ['1','2','3']
list2 = ['3','4','5']
ziplist = zip(list1,list2)
for key, value in dictionary.iteritems():
if '-' in value:
newlist = value.split('-')
ziplist.append(newlist)
for a,b,c in ziplist:
print a,b,c预期产出将是
1 3 6
2 4 7
3 5 8使用上面的代码,我得到了以下错误。
for a,b,c in ziplist:
ValueError: need more than 2 values to unpack我假设'newlist‘列表没有附加到ziplist中。为什么这不管用?
提前谢谢你。
发布于 2014-05-30 10:47:31
您需要实际查看您正在创建的内容:
>>> array1 = ['1','2','3']
>>> array2 = ['3','4','5']
>>> ziplist = zip(array1,array2)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5')]然后
>>> newlist = ['7', '8', '9'] # for example
>>> ziplist.append(newlist)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5'), ['7', '8', '9']]很明显,这不是你想要的。假设您不再访问array1和array2,最简单的方法是再次使用zip将ziplist压平,然后添加newlist,然后再返回-zip。
>>> flatlist = zip(*ziplist)
>>> flatlist
[('1', '2', '3'), ('3', '4', '5')] # almost back to array1 and array2
>>> flatlist.append(newlist)
>>> ziplist = zip(*flatlist)
>>> ziplist
[('1', '3', '7'), ('2', '4', '8'), ('3', '5', '9')]或者,由于在过渡期间不需要压缩列表,所以始终收集平面列表,最后只收集zip:
flatlist = [['1','2','3'], ['3','4','5']]
for value in dictionary.itervalues():
if '-' in value:
flatlist.append(value.split('-'))
for t in zip(*flatlist):
print " ".join(map(str, t))请注意,在ziplist中,每个元组中可能没有确切的3个项,所以我删除了这个假设。
发布于 2014-05-30 10:47:28
如果您不太关心合并列表的内部结构,则只需将附加列表zip到现有列表即可。这将包含嵌套元组(如((1, 3), 6) )的项,但您可以在迭代时解压这些项:
for (a, b), c in zip(ziplist, newlist):
print a, b, chttps://stackoverflow.com/questions/23952615
复制相似问题