簡體   English   中英

使用清單中的未知元素在Python清單中搜尋特定字串

[英]Search a Python list for a specific string using unknown elements in list

我有一個列表,其中包含來自.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)

我已經嘗試實現此較早的文章,並使用Python if (... not in ...)條件嵌套到for循環中以填充listTwo但是當我嘗試打印出listTwo ,未添加任何內容。

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

嘗試創建listTwo時,我是否不比較確切的字符串?

您可以將其轉換為set 像這樣:

listTwo = set(listOne)
print(listTwo)

這只會將唯一元素保留在listOne

由於已經回答了,您可以使用python set。

但是,沒有人問您是否需要保留原始列表的順序,因為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,它將刪除所有重復的字符串。 您還可以將其轉換為列表

使用set刪除列表中的重復項。

listOne = list(set(listOne))

如果列表中的值包含空格,則可以刪除列表中的每個項目並將其set為一set

listOne = list(set([x.strip() for x in listOne]))

請記住,以上兩個答案都不會保留元素的順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM