Python列表.移除()功能

2024-10-03 00:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我刚学会用python编写程序,有一次我被卡住了。我希望你们能解释/帮忙。 提前谢谢。在

items=[]
animals=[]
station1={}
station2={}
import os.path 

def main():
    endofprogram=False
    try:
        filename=input('Enter name of input file >')        
        file=open(filename,'r')
    except IOError:
        print('File does not exist')
        endofprogram=True     

    if (endofprogram==False):
        for line in file:
            line=line.strip('\n')   
            if (len(line)!=0)and line[0]!='#':  
                (x,y,z)=line.split(':')
                record=(x,y,z)
                temprecord=(x,z)
                items.append(record)
                animals.append(x)

                if temprecord[1]=='s1':
                    if temprecord[0] in station1:
                        station1[temprecord[0]]=station1[temprecord[0]]+1
                    else:
                        station1[temprecord[0]]=1
                elif temprecord[1]=='s2':
                    if temprecord[0] in station2:
                        station2[temprecord[0]]=station2[temprecord[0]]+1
                    else:
                        station2[temprecord[0]]=1 
    print(animals)
    for x in animals:
        while animals.count(x)!=1:
            animals.remove(x)
    animals.sort()

    print(animals)


main()   

所以当我打印动物时,它会打印['a01', 'a02', 'a02', 'a02', 'a03', 'a04', 'a05'] 除了a02,列表中的所有元素都将被删除,直到剩下一个元素为止。我不知道为什么这是个例外。在

^{pr2}$

Tags: infalseifmainlineitemsfilenamefile
2条回答

您只需使用set从列表中删除重复项:

list(set(animals))

而不是这样做

^{pr2}$

您在浏览列表时正在修改列表,因此出现错误。在

您可以使用sests

>>> list(set(animals))
['a02', 'a03', 'a01', 'a04', 'a05']
>>> a2=list(set(animals))
>>> a2.sort()
>>> a2
['a01', 'a02', 'a03', 'a04', 'a05']

编辑: 考虑一下这个:

^{pr2}$

当你移除x时,动物会发生变化,因此{}可能会失去它的位置。如果要浏览列表,必须复制并浏览该副本:

>>> animals=['a01', 'a02', 'a02', 'a02', 'a03', 'a04', 'a05']
>>> for x in animals[:]:
...    animals.remove(x)
... 
>>> animals
[]

相关问题 更多 >