【发布时间】:2015-07-18 20:20:11
【问题描述】:
在使用for 结构迭代列表时,我必须找到一种方法来获取item 的位置
other_list = ["line1", "line2", "line3", ... , "line125k+"]
#contains 125k+ items from a txtFile.readlines()
list = ["item1", "item2", "item3"]
#contains 35 items
dict = {"key1":["value1"], "key2":["value2"], "key3":["value3"]}
#contains 35 items too
对于我的dict 中的每个value,我都有一个key,在list 中有一个通讯员item。
list = ["10", "20", "30"]`
dict = {"19":["value1"], "29":["value2"], "39":["value3"]}
字典的第一个键“19”对应于另一个列表中的“10”..
Example:
dict[0] corresponds to list[0]
dict[1] corresponds to list[1]
... and so on.
所以我必须在使用for结构时获取项目位置,这样我才能访问dict中的对应键,并在replace()中使用dict的值
#replace tax1 value
for item in list:
pos_item = item.getPosition() # pos_item = getIteratorValue()
#how can i assign the dict value to a variable?
dict_value = dict[pos_item][value]
#use one variable to search and the other as a replacement
other_list[pos_item].replace("0,00", dict_value)
【问题讨论】:
-
我认为由于迭代器模型,不可能在 foreach 循环中获取索引。你唯一能做的就是在循环之前将一个变量设置为 0 并在每次运行时递增它......
-
dicts 没有顺序,所以你的逻辑如果有缺陷
-
由于字典没有排序,你不能将其项目的位置与列表元素进行比较!
-
根据您想要做的事情,您有 2 个选择,首先使用
OrderdDict而不是dict或对您的 dict 项目进行排序,然后使用不再是字典的排序结果并且是一个列表! -
您可以使用
enumerate(),找出迭代中的当前位置。显然,使用 index 不允许获取 dict 的项目
标签: python python-2.7 dictionary replace