python - 与 Python 中的拆分函数混淆

标签 python

我正在尝试按字母顺序对文件中的单词进行排序。但是,程序根据第一个单词对行而不是单词进行排序。在这里。

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

这是我的输入文件

But soft what light through yonder window breaks 
It is the east and Juliet is the sun 
Arise fair sun and kill the envious moon 
Who is already sick and pale with grief

这就是我希望得到的

['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder'] 

最佳答案

lst.append(words)lst 的末尾附加一个列表,它不会连接 lstwords。您需要使用 lst.extend(words)lst += words

此外,您不应在每次迭代时对列表进行排序,而应仅在循环结束时进行排序:

lst = []
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    lst.extend(words)
lst.sort()
print lst

如果你不想重复单词,使用set:

st = set()
for line in fh:
    lst2 = line.strip()
    words = lst2.split()
    st.update(words)
lst = list(st)
lst.sort()
print lst

关于python - 与 Python 中的拆分函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33419676/

相关文章:

python - 如何使用 sklearn 并行拟合梯度提升模型?

python - 将对象存储在文件中而不是内存中

python - Pandas DataFrame 的立方根

python - 在 Python 中产生和等待子进程

python - 热修复 Tensorflow 模型未使用 .fit() 在 Eager 模式下运行?

python - youtube数据api将哪些分类为无效关键字?

python - 如何获取当前的 python 日志记录配置?

python - Django (postgresql-psycopg2) 连接池 : Simple vs Threaded vs Persistent ConnectionPool

python - 将Docker运行到Kubernetes的问题

python - aiohttp.ClientSession 未使用 'expires' 键设置 cookie