[英]How to get the current value of a Python iterator - dereferencing an iterator without incrementing
[英]Get the iterator value while using a for structure in Python
当使用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
,我得到了一个在list
中具有对应item
的key
。
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)
这里有三个问题,而不是一个。 在Python(和大多数其他语言)中,字典未排序,而replace
返回一个新字符串。 他们没有命令 。 为了解决这个问题,您可以使用OrderedDict
并执行以下操作:
# The dictionary.
dct = OrderedDict([('key1', 'value1'), ('key2', 'value2')]
for pos_item, (item, dict_values) in enumerate(zip(lst, dct.values())):
dict_value = dict_values[value]
other_list[pos_item] = other_list[pos_item].replace('0,00', dict_value)
还要注意,我将dict
重命名为dct
并将list
重命名为lst
,作为dict
和list
内置函数 。 另外,您的代码中可能存在错误,因为您从未真正使用过item
。 我不确定代码中的目的是什么。
这应该是有帮助的:
list = ["item1", "item2", "item3"]
for i in xrange(len(list)): # len(list) returns length of the list
print(list[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.