python - 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)
解决方案
代码正确返回项目的第一次出现的索引。在这种情况下,您最好循环遍历列表索引而不是列表项。还要避免使用名称“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])
推荐阅读
- r - R 语法中的替换/占位符变量
- java - 在 JDeveloper 中,如何指定要使用哪个类的“主”?
- android - 如何将 ImageView 高度与其父级 wrap_content 匹配?(回收站查看项目)
- python - 如何在python中执行shell命令文件
- php - 在 PHP/Wordpress 中实现嵌套数组的过滤器
- unity3d - 如何从 Unity 编辑器脚本启用虚拟现实支持的项目设置?
- android - Android Room 给出错误“预打包的数据库具有无效的架构”但导出的架构是正确的
- python - 在另一个类中使用 self_value
- reactjs - React JS 上下文 API:从另一个组件访问输入值
- sql - HAVING 子句中的 WINDOW 函数替代