2017-10-05 52 views
0

我的數據集,我導入到Python作爲一個列表:計數的連續三分球的數量在2D列表

My dataset which I imported into python as a list

有沒有一種方法可以讓我連續數的三分球數量最多?與第一行一樣,輸出應該是5,因爲有5個連續的3。

import csv 
r = csv.reader(open('motor.csv')) 
list_r = list(r) 


for row in list_r: 
    print 
    count = 0 
    for col in row: 
     if col == '3' and row[row.index(col)+1] == '3': 
      count+=1 

print count 

這是我寫的代碼,但我似乎得到不正確的輸出。

+0

後list_r在代碼中的字面的實際價值,因此對於[MCVE]看起來你指望在這兩個的相鄰對的數量,我們不需要motor.csv同一排。如果有人要求我找到最連續的3個,我不會想到這一點。你也可以在每行之後重置計數,但是直到完成後纔打印結果。 –

+0

考慮'row.index(COL)的值時,有一個以上的''3''行中的'是什麼。 –

回答

0

他們使用下列作爲指導:

import itertools 

def consecutive(group): 
    first, second = itertools.tee(group) 
    second.next() 
    for first, second in itertools.izip(first, second): 
     if second != first + 1: return False 
    return True 

def iterate_submatrix(matrix, t, l): 
    '''yield the horizontals and diagonals of 4x4 subsection of matrix starting at t(op), l(eft) as 4-tuples''' 
    submat = [row[l:l+4] for row in matrix[t:t+4]] 
    for r in submat: yield tuple(r) 
    for c in range (0,4):  
     yield tuple(r[c] for r in submat) 
    yield tuple(submat[rc][rc] for rc in range (0,4)) 
    yield tuple(submat[rc][3-rc] for rc in range(0,4)) 

for item in iterate_submatrix(test_matrix, 0,0): 
    print item, consecutive(item) 
0

首先,row.index(col)總是會產生行的第一價值col的索引。這顯然不是預期的。相反,我建議使用enumerate同時該行中的值和指數遍歷。

其次,你只跟蹤連續3的當前數量,並沒有代碼來跟蹤最大這個計數值。添加另一個變量和else子句來你的代碼可以解決這個問題。

for row in list_r: 
    max_count = current_count = 0 
    for index, value in enumerate(row[:-1]): 
     if value == '3' and row[index+1] == '3': 
      current_count += 1 
     else: 
      max_count = max(current_count, max_count) 
      current_count = 0 
    print count 
1

考慮使用itertools.groupby將列表拆分爲相同值的子序列。然後簡單地返回子序列的最大長度。

from itertools import groupby 
list_r = [ 
    ['3','3','3','3','3','1','3','3','5'], 
    ['1','2','3','3','3','3','3','3','1','3','3','5','3'], 
    ['3','2','3','3','3','3','3','3','1','3','3','5'], 
] 

result = [ 
    max(len(list(g)) for k, g in groupby(row) if k == '3') 
    for row in list_r 
] 

assert result == [5, 6, 6] 
0
import re 

data = [ 
    ['1', '2', '2', '3', '5', '6'], 
    ['1', '2', '3', '3', '4', '5'], 
    ['1', '2', '3', '3', '3', '4'] 
] 

max = 0 
for item in data: 
    match = re.search(r'3+', "".join(item)) 

try: 

    if len(str(match.group(0))) > max: 
     max = len(str(match.group(0))) 
except AttributeError: 
    pass 

print(max)