簡體   English   中英

我在python中有一個扁平化的列表。 如何在不限制每行元素數的同時將列表的元素寫入文件?

[英]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?

因此,假設我有一個扁平化的列表(長度= 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條件?

有任何想法嗎?

功能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,

首先,我不記得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]]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM