简体   繁体   中英

I have a flattened list in python. How do I write the elements of the list into a file, while restricting the number of elements per line?

So, assuming I have a flattened list (with length = 135) where:

matrix_e = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, ...] 

I'd like to write the elements of the list above into a text file, but I can only have a maximum of 16 elements per line. The output should look like this in the text file:

*Elset, elset = matrix
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,34,35,
36,37,38,

For context I am creating a mesh to be analyzed in Abaqus, and apparently you are only allowed 16 elements per line in the mesh file.

Is it possible to set a while condition when using the ','.join method?

Any ideas?

Function chunks splits list at specific size. By making it a function , we make splitting integers dynamic. ie we can change 16 to any other number in future as needed.
We then write it to a file while converting int to str .

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

matrix_e = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45]


with open("out.txt", "w") as txtfile:
    for l in list(chunks(matrix_e, 16)):
        txtfile.write("{},\n".format(','.join([str(i) for i in l])))

Contents of "out.txt"

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
33,34,35,36,37,38,39,40,41,42,43,44,45,

First of all, I can't recall that Abaqus required to have only 16 element numbers per line for sets, so you may want to verify that.

In any way, one way to do it is to iterate over the list, 16 elements a time:

import math
n_lines = math.ceil(len(matrix_e)/16)
lines = []

for i in range(n_lines):
    lines.append(','.join([str(x) for x in matrix_e[16*i:16*i+16]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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