你的榜樣genereates [[], [], [], []]
如果你只是在該文件的頂部添加一個空行,你得到這個[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]
可能還試試這個:
triangle = [ [int(value) for value in line.split(' ') if value.strip()]
for line in open('test.txt') if line.strip()]
列表comprehenssions 可以快於標準循環。測試它,它的工作原理,這個代碼也可以工作,不管空行,它更安全,假設所有條目都是整數。
顯然並不是所有人都喜歡LC這樣:
triangle = []
with open('test.txt', 'r') as f:
for index, line in enumerate(f):
if line.strip():
value = []
for number in line.split(' '):
if number.strip():
try:
value.append(int(number))
except Exception as ex:
print 'Failed to convert %s at line %i' % (number, index)
print 'Exception %s' % str(ex)
raise ex
triangle.append(value)
print triangle
產生[[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]
現在有些人可能喜歡LC有些人可能喜歡for循環的標準,其所有的意見/口味的問題,但肯定的, for循環那些有try ... except ...
這是有點更好,因爲它可以告訴你在哪條線路失敗,但我再次提到,只要所有的值都是整數,LC就可以。
$ python -m timeit 'execfile("test.py")'
10000 loops, best of 3: 198 usec per loop
$ python -m timeit 'execfile("test1.py")'
10000 loops, best of 3: 130 usec per loop
所以基本上35%
改善vs標準,再次它真正的個人。我個人使用非常大的數據集,所以我儘可能地優化它。
沒有必要同時執行'.strip()'和'.split()'操作。 map(int,f.readline())。split())'會工作得很好。 –