【问题标题】:Get the iterator value while using a for structure in Python在 Python 中使用 for 结构时获取迭代器值
【发布时间】: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


【解决方案1】:

这里有三个问题,而不是一个。在 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,如 dict and list builtin functions。此外,您的代码中可能存在错误,因为您实际上从未使用过item;我不确定它在您的代码中的用途是什么。

【讨论】:

    【解决方案2】:

    这应该会有所帮助:

    list = ["item1", "item2", "item3"]
    
    for i in xrange(len(list)): # len(list) returns length of the list
        print(list[i])
    

    【讨论】:

    • xrange 仅适用于 Python 2。
    • 这个问题中有一个python-2.7标签;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2014-12-26
    • 2011-03-15
    • 2016-12-02
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多