python - 如何根据相对列表位置比较python列表中的对象?
问题描述
我有一些要清理的文本数据。该数据的一个不良特征是由特定标记分隔的重复标记。我正在尝试找到一种方法来 (1) 在文本中识别该标记,以及 (2) 删除其中一个重复项。
玩具示例:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
在这里,有两个重复的 'a' 标记,由标记 '!!' 分隔。我正在尝试使用以下方法找到最有效的方法来遍历列表
#pseudo
for word in word_list
if word == "!!":
if word[at word-1] == word[at word+1] # compare words either side of the "!!" marker
del word[at word+1] # removing the duplicate
del word # removing the "!!" marker
output = ['this','is','a','list','I','want','to','clean']
我尝试了几种涉及该enumerate
功能的方法,但似乎无法使其正常工作。
解决方案
使用您的逻辑和enumerate
功能:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
for i, word in enumerate(word_list):
if word == "!!":
if word_list[i-1] == word_list[i+1]:
word_list[i+1] = ""
word_list[i] = ""
print ([x for x in word_list if x])
输出:
['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
推荐阅读
- java - 我如何解析一个 BigInteger 但使用 StringTokenizer
- java - java logger 如何查看它们被调用的文件
- c++ - 相同生成器值的 std::normal_distribution 结果?
- r - 如何计算 r 中 Williams 趋势检验的 ap 值(SAS 中“PROBMC”的类似函数)
- docker - 如何使用 Docker 在 SQL Server 数据库上运行 EF Core 迁移?
- flexbox - 带有 flexbox 表的 Bootstrap 4 手风琴卡有空白
- powershell - 如何从数组中提取数据值并作为变量输入
- c# - 是一个命名空间,但用作变量
- gradle - Gradle build 打印无关的输出
- heroku - (node:4) UnhandledPromiseRejectionWarning: Error: Incorrect login details were provided. (hosting a discord bot)