首页 > 解决方案 > Python为列表中的重复项注册相同的索引,如何找到确切的索引

问题描述

问题:

我想在股票代码项目之后的字符串列表中写“长”或“短”。但如果列表中有重复项,则不会添加“长”或“短”字样。当我打印出索引时,这两个项目都给出了“2”。出了什么问题,我该如何补救?谢谢。

结果:

['Roman', '16.06.2021', **'HARVIA.HE', 'long', 'HARVIA.HE', 'test'**] 

代码:

for list in cleanUserInput:
    list.insert(3, 'test')
    list.insert(5, 'test')
    list.insert(7, 'test')
    for item in list:
        if '.HE' in item:
            longShortIndex = list.index(item) + 1
            if item.startswith('-'):
                list[longShortIndex] = 'short'
                cleanTicker = item[1 : : ]
                list[index] = cleanTicker
                if cleanTicker not in tickers: tickers.append(cleanTicker)
            else:
                list[longShortIndex] = 'long'
                if item not in tickers: tickers.append(item)

标签: pythonloopsindexing

解决方案


代码正确返回项目的第一次出现的索引。在这种情况下,您最好循环遍历列表索引而不是列表项。还要避免使用名称“list”,因为它已被 Python 使用(我已将其替换为“l”)尝试以下操作:

for l in cleanUserInput:
    l.insert(3, 'test')
    l.insert(5, 'test')
    l.insert(7, 'test')
    for i in range(len(l)):
        if '.HE' in l[i]:
            longShortIndex = i + 1
            if l[i].startswith('-'):
                l[longShortIndex] = 'short'
                cleanTicker = l[i][1 : : ]
                l[i] = cleanTicker
                if cleanTicker not in tickers: tickers.append(cleanTicker)
            else:
                l[longShortIndex] = 'long'
                if l[i] not in tickers: tickers.append(l[i])

推荐阅读