使用lis中的未知元素在Python列表中搜索特定字符串

2024-10-04 09:19:18 发布

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

我有一个列表,其中包含来自.csv文件的多个重复字符串:

listOne = ['strOne', 'strTwo', 'strThree', 'strOne', 'strTwo', 'strOne']

并希望从中创建一个新列表,以仅包含唯一的字符串:

listTwo = ['strOne', 'strTwo', 'strThree']

我读了文件,然后像这样填充原始列表:

def createOrigList(filename):
    dataFile = open(filename,'r')
    for line in dataFile:
        origList.append(line)

def createListOne():
    for item in origList:
        tempList = item.split(',')
        strOne = tempList[0].strip()
        listOne.append(strOne)

我尝试实现this earlier post,并使用嵌套在for循环中的Python if (... not in ...)条件来填充listTwo,但是当我尝试打印listTwo时,没有添加任何内容。你知道吗

def createListTwo():
    for item in listOne: 
    item = item.strip()
    if (item not in listTwo):
        listTwo.append(item)

在尝试创建listTwo时,我不是在比较精确的字符串吗?你知道吗


Tags: 文件字符串in列表fordeffilenameitem
3条回答

正如已经回答的那样,您可以使用python集。你知道吗

但是,没有人问您是否需要保持原始列表的顺序,因为set不保持原始列表的顺序。如果需要保持原始列表的顺序,可以使用OrderedDict

from collections import OrderedDict

listOne = ['strOne', 'strTwo', 'strThree', 'strOne', 'strTwo', 'strOne']
listTwo = list(OrderedDict.fromkeys(listOne))
print(listTwo)

给你:

listTwo = [item.strip() for item in set(listOne)]

你可以把它转换成set。像这样:

listTwo = set(listOne)
print(listTwo)

这将只保留listOne中的唯一元素。你知道吗

相关问题 更多 >