1

我寫了一個函數,它允許我運行一個列表,比較這些值與前輩,並聲明列表在哪一點變得「穩定」一定量條目。 列表中的值表示可能達不到穩定點的信號。 我想出了這個:在列表中過濾出穩定值的更多pythonic方法

def unstableFor(points, maxStable): 
    count = 0; 
    prev = points[0] 
    for i in range(1, len(points)): 
     if points[i] == prev: 
      count = count + 1 
     else: 
      count = 0 
      prev = points[i] 
     if count >= maxStable: 
      return i 
    return len(points) - 1 

返回的值,然後使用主叫者爲切掉列表的最後一部分。

它的工作,但是,我很不滿意它看起來有多麻煩。你能想到一個更pythonic,可能純粹功能的方式來執行此過濾操作?

+2

在一個側面說明,我想'count'應該從1開始 –

+3

你也可以顯示一個樣品輸入列表和預期輸出 –

+0

必須的條目是總是連續獲得穩定資格? –

回答

2

使用枚舉和荏苒:

def unstableFor (points, threshold): 
    for i, (a, b) in enumerate(zip(points, points[1:])): 
     count = count + 1 if a == b else 0 
     if count >= threshold: 
      return i 
    return i 
+1

'zip(points,points [1:])'比'zip(points [: - 1],points [1:])在內存使用方面更經濟, Python 2和3分別有相同的結果。 –

+0

@JacquesGaudin謝謝! – Uriel

+0

我相信這是一個非常好的組合和功能:它很清晰,非常緊湊。尼斯。 –

1

下面是一個功能性的方法的草圖。這有點神祕。事實上,我可能會使用你的方法(使用enumerate,因爲這是慣用的方式,而不是range(len(x)))。總之,假設max_stable是3:

>>> from itertools import groupby 
>>> grouped = groupby(enumerate(x), lambda i_e: i_e[1]) 
>>> gen = (g for g in map(lambda e: list(e[1]), grouped) if len(g) >= 3) 
>>> run = next(gen) 
>>> run[2][0] 
10 

這是清理:

>>> from operator import itemgetter 
>>> from itertools import islice 
>>> def unstable_for(points, max_stable): 
...  grouped = groupby(enumerate(points), itemgetter(1)) 
...  gen = (g for g in (tuple(gg) for _, gg in grouped) if len(g) >= max_stable) 
...  run = tuple(islice(gen,1)) 
...  if len(run) == 0: 
...   return len(points) - 1 
...  else: 
...   return run[0][max_stable - 1][0] 
... 
>>> x 
[1, 2, 3, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 9] 
>>> unstable_for(x, 3) 
10 
>>> unstable_for(x, 2) 
3 
>>> unstable_for(x, 1) 
0 
>>> unstable_for(x, 20) 
13 
>>> 

不是很優雅。再次,我會採取必要的解決方案。不過,也許有人有更優雅的功能解決方案。

1

你的代碼對我來說看起來很好:它很容易閱讀和理解。我只是想刪除一些重複,以使它看起來像:

def unstableFor(points, maxStable): 
    prev = None # assuming None is not member of points 
    for i, point in enumerate(points): 
     if point == prev: 
      count = count + 1 
     else: 
      count = 0 
      prev = point 
     if count >= maxStable: 
      break 
    return i 
+0

我會說這是最* Pythonic *的方式。 –

相關問題