生成字符串列表

时间:2018-02-24 20:48:22

标签: python-3.6

这是我的CSV文件中的内容

     Symbol
0     AACAF
1     AACAY
2     AACTF
3      AAGC
4     AAGIY
5     AAIGF
6     AAMAF
7      AAPH
8      AAPT
9      AAST
10    AATDF
11    AATGF
12    AATRL
13    AAUKF
14     AAWC
15     ABBY
16    ABCAF
17    ABCCF
18     ABCE
19    ABCFF
20    ABCZF
21    ABCZY
22    ABEPF
23     ABHD
24     ABHI
25     ABLT
26    ABLYF
27    ABNAF
28     ABNK
29    ABNRY

我想构建一个可以通过三个符号批量创建字符串的函数,例如

'AACAF,AACAY,AACTF'
'AAGC,AAGIY,AAIGF'
'AAMAF,AAPH,AAPT'
'AAST,AATDF,AATGF'
'AATRL,AAUKF,AAWC'
'AABY,ABCAF,ABCCF'
'ABCE,ABCFF,ABCZF'
'ABCZY,ABEPF,ABHD'
'ABHI,ABLT,ABLYF'
'ABNAF,ABNK,ABNRY'

我开始使用python时想要的东西,但我不知道如何完成它。我想我可以使用csv模块来做到这一点。

with open(path, 'r') as csvfile:
    rows=[row for row in csvfile]

    batch_size = 100
    listing = []
    string = ''
    count = 0

    for index, row in enumerate(rows):
        if count >= batch_size:
            listing.append(string)
            string = ''
            count = 0

        ','.join((string,row))
        count += 1

我怎么能用python 3.6做到这一点?

2 个答案:

答案 0 :(得分:0)

with open(path, 'r') as csvfile:
    rows=[row.strip('\n') for row in csvfile]

    batch_size = 100
    listing = []
    string = ''
    count = 0

    for index, row in enumerate(rows[1:]):
        if count >= batch_size or index == len(rows[1:])-1:
            listing.append(string)
            string = ''
            count = 0

        if count == 0:
            string = ''.join((string,row))
        else:
            string = ','.join((string,row))

        count += 1

答案 1 :(得分:0)

arr = pandas.read_csv(path).Symbol.values
symbol_groups = numpy.split(arr, len(arr) // 3)
result = [','.join(symbols) for symbols in symbol_groups]

应该做你正在寻找的事情。