我目前正在做一個基本專案,我想稍后可視化一些傳感器記錄的一些資料。
我有一個帶有數字的檔案:
75
0
0
30
35
32
38
45
53
44
51
62
43
34
56
42
28
32
43
56
43
46
16
33
48
...
我想創建一個串列串列,每個子串列將包含原始串列中的 6 個元素,例如[75,0,0,30,35,32],[38,45,53,44,51,62],...].
f = open("log2.txt", "r")
content = f.readlines()
# Variable for storing the sum
idx = 0
line = []
db = []
# Iterating through the content
for number in content:
print(idx%6)
if idx % 6 == 0:
#newline
db.append(line)
line = []
print("AAAAA")
else:
#continue line
line.append(int(number))
idx = idx 1
print(db)
但結果db只是[[]]。為什么?我怎樣才能做好?
uj5u.com熱心網友回復:
從此處的另一個答案中汲取靈感,我們可以提供具有惰性評估的解決方案。
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i n]
f = open("log2.txt", "r")
content = list(int(line) for line in f)
list_of_lists = list(chunks(content, 6))
這里我們不將中間資料保存在記憶體中,這種方法可用于處理非常大的檔案。
uj5u.com熱心網友回復:
f = open("log2.txt", "r", encoding='utf-8')
content = f.read()
content = content.split()
int_content = []
for i in content:
int_content.append(int(i))
print(int_content)
final = []
# Iterating through the content
rng = 0
temp = []
for number in int_content:
if rng != 6:
temp.append(number)
print(temp)
range = 1
continue
else:
rng = 0
final.append(temp)
temp = []
print(final)
uj5u.com熱心網友回復:
有更簡單的方法可以做到這一點:
f = open("log2.txt", "r")
content = f.readlines()
# now your content looks like this: ['75\n', '0\n', '0\n',...]
content = [int(x.strip()) for x in content]
# now your content looks like this [75, 0, 0, 30, 35, ...]
result = []
while content:
result.append(content[:6])
content = content[6:]
# now your result looks like this: [[75, 0, 0, 30, 35, 32], [38, 45, 53, 44, 51, 62],...]
# and your content variable is empty list
uj5u.com熱心網友回復:
方法1(串列理解):
您可以通過以下行創建一個串列理解f:
f = open("log2.txt", "r")
content = f.readlines()
l = list(map(int, content)) # Converting each line to integer.
l = [l[i:i 6] for i in range(0,len(l), 6)] # Creating lists of 6 elements
print(l)
例如,如果一個檔案包含:
1
2
3
4
5
6
7
8
9
10
11
12
然后輸出是:
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
方法 2(代碼中的改進):
f = open("log2.txt", "r")
content = f.readlines()
line = []
db = []
# Iterating through the content
for idx, number in enumerate(content):
if idx % 6 == 0:
#newline
line = [int(number)] # You need to add that number too!
db.append(line)
else:
#continue line
line.append(int(number))
print(db)
輸出:
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
你做錯了什么?
- 使用變數來跟蹤索引。相反,您可以使用
enumerate()來獲取值和索引。然后您將不需要更新或初始化idx. - 您沒有在
idx % 6 == 0.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/472718.html
上一篇:使用字串將字典轉換為串列字典
下一篇:將句子拆分為串列時如何保留空格?
