所以基本上在我的程序中,在我的列表中的某个项目达不到某个条件后,我将其取出然后通过算法运行它以检查该项目被取出是否会影响列表中的其余项目。 然而我的问题是,当我取出这个项目时,它将我所有其他列表项目推回1索引,所以当我去检查它是否影响其他项目时使用我的算法它会混乱,因为索引在迭代中不断变化for循环。这是我的代码,我将展示一个运行的例子:
library(ggplot2)
ggplot(summary(m3.lr.lsm), aes(x = moral, y = prob, fill = fault)) +
geom_bar(stat = "identity", position = position_dodge(0.9)) +
geom_errorbar(aes(ymin = asymp.LCL, ymax = asymp.UCL), position = position_dodge(0.9), width = 0.2)
我的问题是如何制作它,以便列表保留项目的原始索引后,我删除它的项目,而不是推回它。谢谢。
示例运行:
尚未处于不安全名单的银行的流动资产:
for l in range(len(assets)-1):
print("The current unsafe banks are:",unsafe)
print("Current assets of the banks which are not yet in unsafe list:")
for h in range(len(assets)):
print("Bank ", h ," Current assets: ",assets[h]," millions.")
print()
for i in range(len(assets)-1):
if(assets[i]<=limit):
print("Adding Bank:", i," to the list of unsafe banks.")
unsafe.append(i)
assets.remove(assets[i])
banks.remove(banks[i])
i=float(i)
for j in range(len(banks)):
for k in range(len(banks[j])-1):
if i == banks[j][k]:
banks[j][k+1]=0
assets=current_Assets(banks)
print(banks)
正如你所看到的,它将Bank 4推回Bank 3。
答案 0 :(得分:4)
列表索引始终为0
到len(lst) - 1
。因此,当您从列表中删除项目时,len(lst)
会减一,并且您删除的项目后的所有索引都会更新。没有办法改变这种行为;它完全是设计的,所以你可以在列表的项目上正确迭代。
如果您需要静态索引,那么您应该查看词典。在那里,你可以使用你想要的任何键,包括数字,所以如果从字典中删除一个项目,它只是被删除但不影响其他项目。钥匙刚刚消失了。
>>> banks = {
0: 'bank 0',
1: 'bank 1',
2: 'bank 2',
3: 'bank 3'
}
>>> banks
{0: 'bank 0', 1: 'bank 1', 2: 'bank 2', 3: 'bank 3'}
>>> del banks[2] # remove bank 2
>>> banks
{0: 'bank 0', 1: 'bank 1', 3: 'bank 3'}
答案 1 :(得分:0)
当处理像列表这样的迭代器时,最好不要像正在经历的那样弄乱迭代器。应该创建迭代器的副本,并且应该在循环中使用它。 所以在你的循环开始时应该有:
assets_copy = assets.copy()
并且应该在副本上完成对循环的任何追加或删除。
答案 2 :(得分:0)
我建议改用字典和/或类。以下是如何设置基本类来创建&#34;银行&#34;:
class bank():
def __init__(self, name):
self.name = name
self.currentAssets = 0
self.safe = True
def foo()
limit = 275.0 # some arbitrary threshold, modify as needed
# Initialize your list of banks:
banks = [bank('Bank ' + str(i)) for i in range(7)]
# assign their properties
# you may be reading this from a stream or another input, modify as needed
banks[0].currentAssets = 446.0
banks[1].currentAssets = 250.0
banks[2].currentAssets = 269.0
banks[3].currentAssets = 200.0
banks[4].currentAssets = 375.0
banks[5].currentAssets = 250.0
banks[6].currentAssets = 280.0
# flag the unsafe banks:
for b in banks:
b.safe = (b.currentAssets < limit)
if b.safe:
# do something to the 'safe' banks
else:
print '{} is unsafe with assets: {} millions which is less than the limit of {}'.format(b[i].name, b.currentAssets, limit)
# etc...