给定一个字符串,我需要从出现次数最多的单词到出现次数较少的单词进行排序,并且每个单词在列表中都会出现一次。
s = "hi, you , you, hi, they, no, no, no"
结果将是:
list = ['no','hi','you','they']
您对如何更改我的代码有什么建议? 没有任何收集功能
s="hello, word, word, love, love, love, hi, you"
counter=0
i=0
l=[]
ln=[]
max=1
s=s.split(',')
print(s)
for word in s:
for i in range(len(s)-1):
current_max=s.count(word)
if current_max>max:
max=current_max
temp=s[i]
s[i]=word
s[i+1]=s[i]
i=+1
for word in s:
if word in ln:
continue
else:
ln.append(word)
print(ln)
答案 0 :(得分:0)
您可以将collections.Counter
与set
一起使用:
import collections
s="hi, you, you, hi, they, no, no, no"
d = collections.Counter(s.split(', '))
result = sorted(set(s.split(', ')), key=lambda x:d[x], reverse=True)
输出:
['no', 'hi', 'you', 'they']
答案 1 :(得分:0)
您可以使用Counter.most_common()
方法:
s="hi, you , you, hi, they, no, no, no"
from collections import Counter
print([w for w, _ in Counter(map(str.strip, s.split(','))).most_common()])
打印:
['no', 'hi', 'you', 'they']
编辑:关于您的代码,您可以使用键作为字符串中的单词,用值作为字符串中出现的单词数的值来制作counter
字典。然后根据值对字典进行排序:
s="hi, you , you, hi, they, no, no, no"
s=s.split(',')
counter = {}
for word in s:
w = word.strip()
if w not in counter:
counter[w] = 1
else:
counter[w] += 1
print([i for i, _ in sorted(counter.items(), key=lambda k: -k[1])])
打印:
['no', 'hi', 'you', 'they']
答案 2 :(得分:0)
您可以将sorted
函数与key
参数一起使用。
get_count = lambda word: s.count(word)
new_s = sorted(s, key=get_count, reversed=True)
答案 3 :(得分:0)
受恩佐(Enzo)的启发,几乎没有修改:
s="hello, word, word, love, love, love, hi, you"
s=s.split(', ')
ordered_words = sorted(set(s), reverse=True, key=s.count)
print(ordered_words)
关于您的代码: 您需要使用s.split(',')而不是s.split(','),因为如果第一个单词多次使用,它将被视为2个不同的单词。
答案 4 :(得分:0)
您可以使用Counter
查找每个单词的计数,然后使用其most_common
方法根据出现的顺序对其进行排序
>>> from collections import Counter
>>> s = "hi, you, you, hi, they, no, no, no"
>>> [w for w,_ in Counter(s.split(', ')).most_common()]
['no', 'hi', 'you', 'they']
答案 5 :(得分:0)
请为您的问题找到以下算法和代码。
'''
1. split the words in a string to form list
2. Count number of words repeated in a list
3. Store the "count": "word" as a dictionary
'''
s = s.split(",")
print(s)
def unique(list):
unique_words=[]
for i in list:
if i not in unique_words:
unique_words.append(i)
return unique_words
u=(unique(s))
def count(word,list):
count =0
for i in list:
if i == word:
count +=1
return count
dict = {}
list =[]
for i in u:
x = count(i,s)
if x in dict:
list.append(dict[x])
list.append(i)
dict[x] = list
else:
dict[x] = i
print(dict)
key =[]
for k in dict:
key.append(k)
final_list =[]
for i in key:
v = dict.get(i)
if type(v) ==list:
for u in v:
if type(u) == str:
final_list.append(u)
else:
final_list.append(v)
print(final_list)
答案 6 :(得分:0)
这是一个简单的解决方案:
s =“嗨,你,你,嗨,他们,不,不,不” .split(',')
list = []
for item in s:
if item not in list:
list.append(item)
print(list)
或者您可以进行列表理解:
s = "hi, you, you, hi, they, no, no, no".split(', ')
list = []
[list.append(item) for item in s if item not in list]
print(list)