我在 python 中有几个列,我最终试图合并它们。现在我正在使用 zip 函数,但是在我合并列之后,我将它们输出为 CSV 并且格式很糟糕(而不是保持列分开,zip 在我添加新列时组合列)。这是一个例子:
col1 = [text1, text2, text3, etc]
col2 = [str1, str2, str3, etc.]
col3 = [num1, num2, num3, etc.]
我希望它们像这样组合:
[[text1, str1, num1],
[text2, str2, num2],
[text3, str3, num3]]
从那里我将能够将该矩阵输出为 csv,其中列都是分开的。现在它看起来像这样:
我的代码
file_weights = similarity[0]
file_ranking = zip(filtered_and_cleaned, case_id)[1:]
file_ranking_2 = zip(file_ranking, file_weights)[1:]
输出
[[text1 str1, num1],
[text2 str2, num2],
[text3 str3, num3]]
我明白为什么我正在做的事情不起作用,我只是不知道如何解决它。
请您参考如下方法:
zip指向列列表的指针应该可以解决问题!
col1 = [text1, text2, text3]
col2 = [str1, str2, str3]
col3 = [num1, num2, num3]
print zip(*[col1,col2,col3])
在 Python 3 中 zip返回一个迭代器。因此,您的结果的 list 将提供所需的输出!
也就是说,
print list(zip(*[col1,col2,col3]))
输出格式如下!
[[text1, str1, num1],
[text2, str2, num2],
[text3, str3, num3]]
希望对您有所帮助。
编码愉快!
