2017-01-26 2 views
2

私はリスト(g.ordered)を持っており、そのリストに正しい順序で要素を追加したいと思います。 g.orderedが構成されていますTypeerror添え字なし

# all values are floats 
g.ordered = [ 
    [[a, b, c, d...], [A]], 
    [[e, f, g, h...], [B]]... 
] 

# Where A is < B is < ... 

私は動作するはずの機能を書かれている

x = [[q, w, e, r...], [C]] 
# Where C can be any float 

を追加したい:

def insert(x): 
    for i in range(len(g.ordered)): 

     print(g.ordered[i][1]) 
     print(x[1]) 

     if(g.ordered[i][1] > x[1]): 
      break 
     g.ordered = g.ordered[:i] + x + g.ordered[i:] 

今、私はいけない部分を理解: ときIそれを印刷するプリントステートメントを含めます:

>>> g.ordered[0][1] 
A 
>>> X[1] 
C 

しかし、それが印刷されると、エラーが表示されます。

print(g.ordered[i][1]) 
TypeError: 'float' object is not subscriptable 

これは、次の行がすでに完了した後です。

プリントと

完全なエラー:

-4.882695743122578 # this is the A value 
0.01 # this is the C value 
# those where the expected prints which are in line 50 and 51 respecively 

Traceback (most recent call last): 
    File "/home/jjrreett/Genetic.py", line 57, in <module> 
    insert([[1,2,3,4,5], 0.01]) 
    File "/home/jjrreett/Genetic.py", line 50, in insert 
    print(g.ordered[i][1]) 

はTypeError: 'フロート' オブジェクトは、添字化

+2

at line 49 print g.ordered [i]浮動小数点の場合は答えが間違っています – awiebe

答えて

0

ではありませんあなたが本当にg.ordered[i]を意味するときは、計算の結果にg.orderedを設定している:

def insert(x): 
    for i in range(len(g.ordered)): 
     ... 
     g.ordered[i] = g.ordered[:i] + x + g.ordered[i:] 
0

誤ってリストを再構築します。

g.ordered = g.ordered[:i] + x + g.ordered[i:] 

でなければなりません:

g.ordered = g.ordered[:i] + [x] + g.ordered[i:] 

また、この文は、ループの外でなければなりません。しかし、より堅牢なソリューションがg.orderedの最後に新しいリストを追加して、ABCでリストを再ソートすることになります。でも、すべてのことを固定した後

def insert(x): 
    g.ordered.append(x) 
    g.ordered = sorted(g.ordered, key=lambda x:x[1][0]) 
+0

ありがとうございます。あなたは100%正しいです。毎回リストを並べ替えることの問題は、これがループになるので、私は時間が欲しいとは思っていません。 –

0
def insert(x): # you later try to subscript this float 
    for i in range(len(g.ordered)): 

     print(g.ordered[i][1]) 

     # On the following line, `x` is the float you passed in 
     # as a parameter. You can't subscript a float. 
     print(x[1]) 

     # Here again, you subscript the float `x` 
     # also, g.ordered[i][1] is a single element list `[A]` 
     # and not a value. g.ordered[i][1][0] would be `A` 
     if(g.ordered[i][1] > x[1]): 
      break 

     # This is not how you insert a value into a list. 
     # Should be g.ordered[:i] + [x] + g.ordered[i:] 
     # and not g.ordered[:i] + x + g.ordered[i:] 
     # Or, better yet, just use g.ordered.insert(i, x) 
     g.ordered = g.ordered[:i] + x + g.ordered[i:] 

、あなたの関数はまだしませんあなたがしようとしていることをしなさい。 [[q, w, e, r, ...], [C]]という形式の構造ではなく、単一の値(パラメータx)をg.orderedに挿入します。

さらに、どこに挿入するかを決定するために使用しているロジックは、期待通りのものではないようです。

DYZのソリューションは、あなたの問題を非常にエレガントに解決するはずです。

しかし、彼のソリューションでは、浮動小数点だけでなく、[[q, w, e, r, ...], [C]]という形式の構造を渡す必要があることに注意してください。あなたが言っていたエラーに基づいて、正しいフォームの構造ではなく、単一の浮動小数点値を渡しているようです。だから、それを適切に構築するために必要なコードが必要です。

関連する問題