以下是代码。为什么表现如此?有什么替代方案?
line2 = ["a", "b","c","d","e","f","g","a","c", "d","e","g","h",]
for x in line2:
print("X value is:", x, " and its index is:", line2.index(x))
输出是:
X value is: a and its index is: 0
X value is: b and its index is: 1
X value is: c and its index is: 2
X value is: d and its index is: 3
X value is: e and its index is: 4
X value is: f and its index is: 5
X value is: g and its index is: 6
X value is: a and its index is: 0
X value is: c and its index is: 2
X value is: d and its index is: 3
X value is: e and its index is: 4
X value is: g and its index is: 6
X value is: h and its index is: 12
为什么不递增?我该如何解决?我需要增加索引吗?而不是索引,我们有像X的位置
答案 0 :(得分:4)
如果你只使用enumerate,那么在每次迭代中使用index
调用非常代价很高。此外,请注意索引如何工作,因为您将始终只有第一次获得价值。
for index, value in enumerate(line2):
print("X value is:", value, " and its index is:", index)
关于成本的实施方式以及此答案的工作原理。您无法将index
的功能与enumerate
的功能进行真正比较。
您的第一个列表将是O(n)
,当然因为您只是遍历整个列表。但是,通过对index
的每次调用,这本身就是O(n)
。就效率低下而言,这是巨大的。
enumerate
遍历您的列表一次,提供一个元组结果,其中第一个值代表您的索引,第二个值只是列表中的 next 值,因此只提供给您O(n)
复杂度print
。因此,您提供的解决方案中的CREATE TABLE orders (
id INT NOT NULL AUTO_INCREMENT,
orderNumber INT,
productId INT,
customerId INT,
orderDate DATETIME default CURRENT_TIMESTAMP,
PRIMARY KEY(id),
FOREIGN KEY (customerId) REFERENCES customers(id) ,
FOREIGN KEY (productId) REFERENCES products(id));
语句不需要任何费用,因为您只需输出已有的值而无需任何额外的计算。