繁体   English   中英

在Python中使用for结构时获取迭代器值

[英]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中具有对应itemkey

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)

查看enumeratezip

还要注意,我将dict重命名为dct并将list重命名为lst ,作为dictlist内置函数 另外,您的代码中可能存在错误,因为您从未真正使用过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM