Python Zip List Append

dly*_*zen 0 python

编辑:添加更多信息

如何将新列表"附加"到已压缩的列表中.执行此操作的主要原因是,我需要扫描字典并使用特定字符拆分任何字段,并将结果列表添加到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
Run Code Online (Sandbox Code Playgroud)

预期的产出将是

1 3 6
2 4 7
3 5 8
Run Code Online (Sandbox Code Playgroud)

使用上面的代码我得到以下错误.

for a,b,c in ziplist:
ValueError: need more than 2 values to unpack
Run Code Online (Sandbox Code Playgroud)

我假设'新列表'列表没有附加到ziplist.为什么这不起作用?

先感谢您.

jon*_*rpe 5

您需要实际查看您正在创建的内容:

>>> array1 = ['1','2','3']
>>> array2 = ['3','4','5']
>>> ziplist = zip(array1,array2)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5')]
Run Code Online (Sandbox Code Playgroud)

然后

>>> newlist = ['7', '8', '9'] # for example
>>> ziplist.append(newlist)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5'), ['7', '8', '9']]
Run Code Online (Sandbox Code Playgroud)

显然,这不是你想要的.最简单的方法,假设你不再有权访问,array1并且array2是再次ziplist使用zip,然后添加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')]
Run Code Online (Sandbox Code Playgroud)

或者,由于您在过渡期间不需要压缩列表,因此请始终收集整个列表,并且仅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))
Run Code Online (Sandbox Code Playgroud)

请注意,每个元组中可能没有正好3个项目ziplist,因此我删除了该假设.