开发者

writing some numbers into csv like comparision matrix

I am using python to write some comparison value as bel开发者_StackOverflow中文版ow mentioned:

ids = [1, 2, 3] 
vals = [0.0, 0.71, 0.89, 0.71, 0.0, 0.77, 0.89, 0.77, 0.0]

where ids are id_number (int) of 3 chemical compounds derived from a database and vals are comparison values with each others ......but I want these ids and vals TO BE WRITTEN INTO A CSV FILE like below:

    1        2        3

1   0.0      0.71     0.89 

2   0.71     0.0      0.77

3   0.89     0.77     0.0

ONLY UPPER OR LOWER TRINGULAR MATRIX WRIITEN INTO CSV WILL BE BETTER


Using the csv module:

import csv

ids= [1, 2, 3] 
vals = [0.0, 0.71, 0.89, 0.71, 0.0, 0.77, 0.89, 0.77, 0.0]

with open('/tmp/test.csv','w') as f:
    writer=csv.writer(f, delimiter='\t',lineterminator='\n',)
    writer.writerow(['']+ids)
    for i,row in enumerate(zip(*[iter(vals)]*3),1):
        writer.writerow((i,)+row[:i])

This creates a lower triangular matrix:

    1   2   3
1   0.0
2   0.71    0.0
3   0.89    0.77    0.0

The grouper recipe, zip(*[iter(vals)]*3), was used to group vals into 3-tuples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜