简体   繁体   English

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

[英]Get the iterator value while using a for structure in Python

I must find a way to get the item position when iterating over a list using a for structure 当使用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

For each value inside my dict , i got a key that have a correspondent item in the list . 对于我的dict每个value ,我得到了一个在list中具有对应itemkey

list = ["10", "20", "30"]`
dict = {"19":["value1"], "29":["value2"], "39":["value3"]}

the dict's first key, "19", corresponds to the "10" inside the other list.. 字典的第一个键“ 19”对应于另一个列表中的“ 10”。

Example:
dict[0] corresponds to list[0]
dict[1] corresponds to list[1]
... and so on.

So i have to get the item position while using a for structure , so then i can access the correspondent key in the dict, and use the dict's value in a replace() 所以我必须在使用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)

There are three issues here, not one. 这里有三个问题,而不是一个。 In Python (and most other languages), dictionaries aren't sorted, and replace returns a new string. 在Python(和大多数其他语言)中,字典未排序,而replace返回一个新字符串。 They have no order . 他们没有命令 In order to get around this, you can use an OrderedDict and do something like: 为了解决这个问题,您可以使用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)

Look into enumerate and zip . 查看enumeratezip

Also notice that I renamed dict to dct and list to lst , as dict and list builtin functions . 还要注意,我将dict重命名为dct并将list重命名为lst ,作为dictlist内置函数 In addition, there may be a bug in your code, as you are never actually using item ; 另外,您的代码中可能存在错误,因为您从未真正使用过item I'm not sure what it's purpose in your code was. 我不确定代码中的目的是什么。

This should be helpfull: 这应该是有帮助的:

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