python - 如何删除列表中第一次出现的整数

标签 python python-3.x

这是我的代码:

positions = []
for i in lines[2]:
    if i not in positions:
        positions.append(i)
print (positions)
print (lines[1])
print (lines[2])

输出是:

['1', '2', '3', '4', '5']
['is', 'the', 'time', 'this', 'ends']
['1', '2', '3', '4', '1', '5']

我希望变量“positions”的输出是; ['2','3','4','1','5'] 因此,与其从变量“lines[2]”中删除第二个重复项,不如删除第一个重复项。

最佳答案

您可以反转列表,创建位置,然后按照@tobias_k 在评论中提到的那样将其反转:

lst = ['1', '2', '3', '4', '1', '5']

positions = []
for i in reversed(lst):
    if i not in positions:
        positions.append(i)

list(reversed(positions))
# ['2', '3', '4', '1', '5']

关于python - 如何删除列表中第一次出现的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309238/

相关文章:

python - 在 pandas (python) 中处理 5000 万行

html - Beautifulsoup 解析特定标签下的数据

python - 每个嵌套列表中的元素数

Python:如何在我的时间序列中删除每天的前 5 分钟?

python - 如何将字符串附加到 Python 中的路径?

javascript - Python Flask - 否 'Access-Control-Allow-Origin'

Python循环函数根据多列的Groupby创建新列

python - 获取复数的相位

python - ElementTree findall() 返回空列表

Python tkinter 标签