【问题标题】:python find unique and put it alphabetical orderpython找到唯一并按字母顺序排列
【发布时间】:2019-10-09 15:06:53
【问题描述】:

我需要找到一个文本文件并打印出唯一的单词并按字母顺序排列 我知道如何读取文件并按字母顺序排列,但我遇到了排序和唯一性的问题(老实说,我不知道如何做到这一点)

我遇到的另一个问题是,虽然它给了我按字母顺序排列的单词,但每次找到一个单词时都会给我“\n”

文本文件: 麦克风, 萨拉 萨拉 亚当 威廉

A= open('Wordfile.txt')
line=sorted(A.readlines())

while len(line)!=0:
print(line, end =' ')
line=A.readline()


A.close();

输出:Adam, mike \n, sara \n, sara\n, william\n

【问题讨论】:

  • 你能添加一个你预期输出的例子吗?

标签: python file unique alphabetical


【解决方案1】:

我们可以做到:

A = open('Wordfile.txt')
lines = sorted(list(set([line.rstrip() for line in A])))    # Used rstip() to remove '\n' and set() to make items unique.

for line in lines:
    print(line, end =' ')

A.close()

【讨论】:

  • 啊,是的,谢谢,我必须记住“设置”是一个东西
猜你喜欢
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 2020-03-29
相关资源
最近更新 更多