我有一个列表(g.ordered),我想以正确的顺序向该列表添加一个元素。 g.ordered结构化:
# 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:]
现在我不明白的部分: 当我包含print语句时,它会打印我想要的内容:
>>> 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:&#39; float&#39;对象不可订阅
答案 0 :(得分:0)
当您真正想要g.ordered
时,您正在设置g.ordered[i]
到计算结果:
def insert(x):
for i in range(len(g.ordered)):
...
g.ordered[i] = g.ordered[:i] + x + g.ordered[i:]
答案 1 :(得分: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])
答案 2 :(得分: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:]
即使在解决了所有这些问题之后,你的功能仍然不会按你的意愿行事。它将单个值(参数x
)插入到g.ordered而不是[[q, w, e, r, ...], [C]]
形式的结构中。
此外,您用来决定插入位置的逻辑似乎不会像您期望的那样。
DYZ的解决方案看起来应该非常优雅地解决你的问题。
但请记住,使用他的解决方案,您需要传递[[q, w, e, r, ...], [C]]
形式的结构,而不仅仅是浮点数。基于您提到的错误,您似乎传递的是单个浮点值而不是正确形式的结构。因此,您仍然需要正确构建所需的任何代码。