所以,假设我有一个扁平列表(长度= 135),其中:
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, ...]
我想将上面列表中的元素写入文本文件,但每行最多只能有16个元素。输出应该在文本文件中如下所示:
*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,
对于上下文我正在创建一个要在Abaqus中进行分析的网格,显然在网格文件中每行只允许16个元素。
使用','。join方法时是否可以设置while条件?
有什么想法吗?
答案 0 :(得分:3)
函数chunks
按特定大小拆分列表。通过使它成为一个函数,我们使分裂整数动态化。即根据需要,我们将来可以将16更改为任何其他数字
然后,我们会在将int
转换为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])))
“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,
答案 1 :(得分:1)
首先,我不记得Abaqus要求每行只有16个元素编号,所以你可能想验证它。
无论如何,一种方法是迭代列表,一次16个元素:
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]]))