简体   繁体   English

如何将两个列表合二为一

[英]How to combine two list in to one with two columns

Two lists 两张清单

x = ['a','b','c','d','e']
y = ['s','t','u','v','w','x','y','z']

How do I combine these two results and dump these to a CSV file with two columns, I have tried using zip(x,y) but it removes some end objects of list y . 我如何合并这两个结果并将其转储到具有两列的CSV文件中,我尝试使用zip(x,y)但它删除了列表y某些最终对象。 Most of the solution provides for those cases where objects in x and y are equal, as you can see in my case that is not. 大多数解决方案都针对xy中的对象相等的情况,如我所见,情况并非如此。

Use the itertools.izip_longest() function instead, and tell it what to use for those missing columns; 改用itertools.izip_longest()函数 ,并告诉它对那些缺少的列使用什么方法; for a CSV file an empty string would work: 对于CSV文件,可以使用空字符串:

for row in izip_longest(x, y, fillvalue=''):
    # ...

Note that in Python 3, the i prefix was dropped from the function name. 请注意,在Python 3中,从函数名称中删除了i前缀。

If you are writing these to a CSV file, you can send the whole object to the csv.writer.writerows() function directly: 如果要将这些内容写入CSV文件,则可以将整个对象直接发送到csv.writer.writerows()函数:

import csv
from itertools import izip_longest

with open(filename, 'wb') as outf:
    writer = csv.writer(outf)
    writer.writerows(izip_longest(x, y, fillvalue=''))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM