列表元素删除和添加,

时间:2018-05-03 05:26:13

标签: python python-2.7

请不要将此标记为已回答的问题,因为我认为这不是关于一般程序,但这是一个我没有意识到的具体事情。 所以问题是当我运行该程序时,它应首先删除" araba"字符串然后插入" car"字符串在其现有位置。所以我每次都提起dict并打印它但没有任何反应? THX

tr_mean=["araba","otobus","kus"]
en_mean=["car","bus","dog"]
dictionary={}
for x in tr_mean:
  index=tr_mean.index(x)
  dictionary[x]=en_mean[index]



print tr_mean.index("araba")
for x in tr_mean:
  index=tr_mean.index(x)
  dictionary[x]=en_mean[index]
print words
del tr_mean[tr_mean.index("araba")]
for x in tr_mean:
  index=tr_mean.index(x)
  dictionary[x]=en_mean[index]
print words
tr_mean.insert(0,"car")
for x in tr_mean:
  index=tr_mean.index(x)
  dictionary[x]=en_mean[index]

print words

1 个答案:

答案 0 :(得分:1)

tr_mean = ["araba", "otobus", "kus"]
en_mean = ["car", "bus", "dog"]
dictionary = {}
for x in tr_mean:
    index = tr_mean.index(x)
    dictionary[x] = en_mean[index]

print tr_mean.index("araba")

在这里,你只是在做同样的事情,不需要。

# for x in tr_mean:
#     index = tr_mean.index(x)
#     dictionary[x] = en_mean[index]

您没有定义words,我猜您打算使用dictionnary

print dictionary

"araba"移除tr_meantr_mean现在为["otobus", "kus"]

del tr_mean[tr_mean.index("araba")]

之后,我猜你试图“重置”词典

for x in tr_mean:
        index = tr_mean.index(x)
        dictionary[x] = en_mean[index]
    print dictionary

但你所做的只是:

dictionary["otobus"] = "bus"
dictionary["kus"] = "dog",

araba仍然存在于dictionnary !!!

在分配新值之前,请使用dictionary.clear()

清除字典
dictionary.clear()
for x in tr_mean:
    index = tr_mean.index(x)
    dictionary[x] = en_mean[index]
print dictionary

或者更好的是,删除最后一段代码,只需从"araba"删除dictionary

del dictionary["araba"]

其他所有事情都保持不变。

tr_mean.insert(0, "car")
for x in tr_mean:
    index = tr_mean.index(x)
    dictionary[x] = en_mean[index]

print dictionary 

编辑: 如果您想使用“araba”的值将“car”添加为词典的新键,您可以执行以下操作:

dictionary["car"] = dictionary.pop("araba")

.pop()将删除“araba”键并将与“araba”相关联的值提供给新密钥dictionary["car"]