在最终输出中删除不需要的“[”和“]”
Remove unwanted '[' and ']' in final output
你好,我正在编写一个函数,它接受一个包含文本的文件,returns 是文件中最常见的单词。我当前的代码如下所示:
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]]
这个 return 是最常用的词。但是,它 return 以 ['word here'] 格式存储它,而它应该 return 格式 'word here'。 (不在方括号中,而仅在 's 中)。
如有任何帮助,我们将不胜感激!
在Python中,列表用[]
表示。例如,[1,2,3,4,5]
是一个列表。为了访问单个元素,我们使用索引。所以如果 a = [1,2,3,4,5]
是一个列表,第一个元素可以通过 a[0]
访问,第二个元素可以通过 a[1]
等等。
您的代码 returns 整个列表而不是元素。返回列表的 [0]
元素的简单修改实现了您的 objective.
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]][0]
print(approximate_song('README.txt'))
你好,我正在编写一个函数,它接受一个包含文本的文件,returns 是文件中最常见的单词。我当前的代码如下所示:
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]]
这个 return 是最常用的词。但是,它 return 以 ['word here'] 格式存储它,而它应该 return 格式 'word here'。 (不在方括号中,而仅在 's 中)。
如有任何帮助,我们将不胜感激!
在Python中,列表用[]
表示。例如,[1,2,3,4,5]
是一个列表。为了访问单个元素,我们使用索引。所以如果 a = [1,2,3,4,5]
是一个列表,第一个元素可以通过 a[0]
访问,第二个元素可以通过 a[1]
等等。
您的代码 returns 整个列表而不是元素。返回列表的 [0]
元素的简单修改实现了您的 objective.
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]][0]
print(approximate_song('README.txt'))