Python 使用追加删除重复单词从文件创建排序列表



我目前正在学习 python 课程,6 小时 + 后我迷失了方向。作业指导学生创建一个程序,其中用户输入文件名,python打开文件并构建一个没有重复项的排序单词列表。方向非常明确,必须使用 For 循环和追加。" 对于每行上的每个单词,请检查该单词是否已在列表中,如果没有,则将其附加到列表中。">

fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    line = line.strip()
    words = line.split()
for words in fh:
    if words in 1st:continue
        elif 1st.append
1st.sort()
print 1st 

单独使用set()会更容易,但根据赋值说明,这将是一个很好的实现。 与仅list版本相比,它的速度非常快!

from collections import Set
def get_exclusive_list(fname):
    words = []
    with open(fname.txt, 'r') as file_d:
        data = file_d.read()
    [words.extend(li.split(' ')) for li in data.splitlines()]
    data = []
    already_seen = set()
    for thing in words:
        if thing not in already_seen:
            data.append(thing)
            already_seen.add(thing)
return data

# The better implementation
def get_exclusive_list_improved(fname):
    words = []
    with open(fname.txt, 'r') as file_d:
        data = file_d.read()
    [words.extend(li.split(' ')) for li in data.splitlines()]
    return list(set(words))

不确定以下循环应该做什么 -

for words in fh:
    if words in 1st:continue
        elif 1st.append

以上不执行任何操作,因为在控制到达此部分之前,您已经用尽了文件fh

您应该在内部放置一个内部循环 - for line in fh: - 逐个检查words列表中的单词,如果它还没有,则附加到lst

另外,你应该做lst.append(word)

另外,我认为您的if..elif块也不是有效的语法。

你应该做一些类似 xample 的事情——

for line in fh:
    line = line.strip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)

最新更新