我有一个列表,其中包含来自.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
时,我不是在比较精确的字符串吗?你知道吗
正如已经回答的那样,您可以使用python集。你知道吗
但是,没有人问您是否需要保持原始列表的顺序,因为set不保持原始列表的顺序。如果需要保持原始列表的顺序,可以使用
OrderedDict
:给你:
你可以把它转换成
set
。像这样:这将只保留
listOne
中的唯一元素。你知道吗相关问题 更多 >
编程相关推荐