这是我的编程问题的示例代码,要求拆分字符串并对单个单词进行排序以避免重复。我知道这段代码100%正确,但我不确定lst = list()
代码行的用途是什么?
程序如何知道将文件romeo放入列表中?
fname = input("Enter file name: ")
romeo = open(fname)
lst = list()
for line in romeo:
line = line.rstrip()
line = line.split()
for e in line:
if e not in lst:
lst.append(e)
lst.sort()
print(lst)
答案 0 :(得分:0)
也许你对文件的迭代感到困惑。迭代允许我们将文件视为一个容器,可以像我们对任何其他容器一样迭代,如list或set或dict.items()。
同样lst = list()
表示lst = []
。这与文件迭代无关。
答案 1 :(得分:0)
List是一个python对象。在解释器中键入help(list)。你会看到你的屏幕
通常对于某些编程语言,调用className()会创建类型类的对象。例如在C ++中
class MyClass{
var declarations
method definitions
}
MyObj=MyClass()
上面代码中的MyObj是您的类MyClass的对象。为您的代码应用相同的东西 lst是在Python中预定义的列表类的对象类型,我们称之为内置数据结构。
因此,您的上述lst定义会将lst初始化为空列表。
帮助部分显示了两种类型的列表类构造函数,它们以不同的方式使用。第二种类型的构造函数
list(iterable)
将创建一个已创建序列的列表。例如
tuple1=(1,'mars')
new_list=list(tuple1)
print(new_list)
将使用可迭代的元组创建新列表new_list。
答案 2 :(得分:0)
有关更多见解,请参阅下文:
# the following line stores your input in fname as a str
fname = input("Enter file name: ")
# the following line opens the file named fname and stores it in romeo
romeo = open(fname)
# next line creates an empty list through the built in function list()
lst = list()
# now you go through all the lines in the file romeo
# each word is assigned to the variable line sequentially
for line in romeo:
# strip the line of evntual withespaces at the end of the string
line = line.rstrip()
# split the string on withespaces and stores each element
# of the splitted string in the list line which will then contain every
# word of the line.
line = line.split()
# now you go through all the elements in the list line
# each word is assigned to e sequentially
for e in line:
# now if the word is not contained in the list lst
if e not in lst:
# it inserts the word to the list in the last postion of the list lst.
lst.append(e)
# sort the list alphabetically
lst.sort()
print(lst)
一些注意事项:
您可能希望在脚本末尾添加romeo.close()
以关闭文件
请务必注意,并非所有文件都存储在lst列表中。由于if e not in lst:
答案 3 :(得分:-1)