Python ZIP函数提供意外输出

时间:2016-12-13 09:46:49

标签: python python-2.7

我正努力让zip Python 2.7函数来提供我需要的输出。

我拥有的数据示例:

print(score_data[0:3])
[['0/1:7,3:10:99', '0/0:3:3:99'], ['0/0:12:12:99', '0/1:11,7:18:99'], ['0/1:8,7:15:99', '0/1:14,4:18:99']]

我想要的输出类型

[['0/1:7,3:10:99','0/1:8,7:15:99', '0/0:12:12:99'], [ '0/1:11,7:18:99','0/0:3:3:99', '0/1:14,4:18:99']]

我得到的输出:

print(zip(score_data[0:3]))
[(['0/1:7,3:10:99', '0/0:3:3:99'],), (['0/0:12:12:99', '0/1:11,7:18:99'],), (['0/1:8,7:15:99', '0/1:14,4:18:99'],)]

1 个答案:

答案 0 :(得分:6)

您错误地将zip应用于一个列表。 zip没有抱怨,但它只是在列表中添加了一个元组维度,没有多大用处:

>>> list (zip([1,2,3,4]))
[(1,), (2,), (3,), (4,)]

您需要将子列表展开为位置参数(使用*运算符)以传递给zip

z = [['0/1:7,3:10:99', '0/0:3:3:99'], ['0/0:12:12:99', '0/1:11,7:18:99'], ['0/1:8,7:15:99', '0/1:14,4:18:99']]

print(list(zip(*z)))   # convert to list for python 3 compat.

结果:

[('0/1:7,3:10:99', '0/0:12:12:99', '0/1:8,7:15:99'), ('0/0:3:3:99', '0/1:11,7:18:99', '0/1:14,4:18:99')]

请注意,默认情况下zip会发出元组。改为创建list类型:

print([list(x) for x in zip(*z)])

结果:

[['0/1:7,3:10:99', '0/0:12:12:99', '0/1:8,7:15:99'], ['0/0:3:3:99', '0/1:11,7:18:99', '0/1:14,4:18:99']]