2013-09-26 156 views

Trả lời

7

Bạn có thể sử dụng itertools.islice:

import itertools 

i, j = 10, 20 
with open(trainFile, 'rt') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
    for row in itertools.islice(spamreader, i, j+1): 
     print (', '.join(row)) 

Alternative (mã sau đây có thể vì csv.reader chấp nhận một iterable):

LƯU Ý : chỉ hoạt động khi các hàng CSV không chứa dòng mới.

import itertools 

i, j = 10, 20 
with open(trainFile, 'rt') as csvfile: 
    spamreader = csv.reader(itertools.islice(csvfile, i, j+1), 
          delimiter=' ', quotechar='|') 
    for row in spamreader: 
     print (', '.join(row)) 
+0

@kworr, Cảm ơn bạn đã nhận xét. Tôi đề cập đến điều đó. – falsetru

+1

Trong thay thế của bạn các giá trị của 'i' và' j' không được tham chiếu ... vì vậy tôi nghi ngờ nó hoạt động như được hiển thị. – martineau

+0

@martineau, Cảm ơn bạn đã chỉ ra. Tôi đã cập nhật thay thế cho phù hợp. – falsetru

1

Sử dụng islice, ví dụ:

rows_1_to_50 = itertools.islice(spamreader, 0, 50) 
for row in rows_1_to_50: 
    pass 
1

Một thực hiện itertools sử dụng dropwhiletakewhile

from itertools import takewhile, dropwhile 
trainFile = 'x.1' 
low_lim = 3 
high_lim = 6 
with open(trainFile, 'rt') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
    g = (x for x in enumerate(spamreader, 1)) 
    g = dropwhile(lambda x: x[0] < low_lim, g) 
    g = takewhile(lambda x: x[0] <= high_lim, g) 
    for row in g: 
     print (', '.join(row[1])) 
+0

Khi bạn nói 'trainFile = 'x.1'' đề cập đến đường dẫn đầy đủ, đúng không? –

+0

@ MattO'Brien, đúng vậy. Có thể hoàn thành hoặc tương đối – iruvar