Python:组合两个列表,但它组合了另一个列表中的一行

问题描述 投票:0回答:2

我正在尝试将两个列表组合成一个csv,并让它为第二个列表的每一行输出一行。

a.csv

1  
2  
3  

b.csv

a,x  
b,y  
c,z  

输出: c.csv

1|a|x  
2|a|x  
3|a|x  
1|b|y  
2|b|y  
3|b|y  
1|c|z  
2|c|z  
3|c|z  

因此,对于每行“a”组合每行“b”,并获得“c”中的列表。

注意,我没有必要将“b”分开来重新排序列,保持原始顺序正常。 似乎需要一个循环,但我没有运气这样做。


回答(输出不完美,但我需要的确定):

import csv
from itertools import product

def main():
    with open('a.csv', 'rb') as f1, open('b.csv', 'rb') as f2:
        reader1 = csv.reader(f1, dialect=csv.excel_tab)
        reader2 = csv.reader(f2, dialect=csv.excel_tab)

        with open('output.csv', 'wb') as output:
            writer = csv.writer(output, delimiter='|', dialect=csv.excel_tab)
            writer.writerows(row1 + row2 for row1, row2 in product(reader1, reader2))

if __name__ == "__main__":
    main()

输出文件:

1|a,x
1|b,y
1|c,z
2|a,x
2|b,y
2|c,z
3|a,x
3|b,y
3|c,z

是的“|”只是其中一个分隔符。 很高兴知道如何获得“1 | a | x”等等。

python python-2.7 csv
2个回答
0
投票

一种方法是使用pandas

import pandas as pd

df = pd.concat([pd.read_csv(f, header=None) for f in ('a.csv', 'b.csv')], axis=1)

df.to_csv('out.csv', sep='|', index=False, header=False)

0
投票

使用itertools.product的本机Python方法:

from itertools import product

#read file a, remove newline, replace commas with new delimiter and ignore empty lines
a = [line[:-2].strip().replace(",", "|") for line in open("a.csv", "r") if line[:-2].strip()]
#read file b, leave newline in string
b = [line.replace(",", "|") for line in open("b.csv", "r") if line[:-2].strip()]
#combine the two lists
c = ["|".join([i, j]) for i, j in product(a, b)]
#write into a new file
with open("c.csv", "w") as f:
    for item in c:
        f.write(item)
#output
1|a|x  
1|b|y  
1|c|z 
2|a|x  
2|b|y  
2|c|z 
3|a|x  
3|b|y  
3|c|z
© www.soinside.com 2019 - 2024. All rights reserved.