简体   繁体   English

如何将列表中的单词提取到新列表中?

[英]how to extract the words from a list to a new list?

I want to extract the words from the biggest number which is 3 with is love to the smallest number我想从最大的数字 3 中提取单词,并且是爱到最小的数字

[1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']

the result will be:结果将是:

['love','word','hello', 'hi','you']

Thanks for the help!谢谢您的帮助!

I have this code but I'm stuck because of error message TypeError: sort() takes no positional arguments :我有这段代码,但由于错误消息TypeError: sort() takes no positional arguments而卡住了:

s="hello, word, word, love, love, love, hi, you"


def f(s):
    all=s.split(',')
    print(all)
    uni=[]
    count=[]
    sorted=[]
    for word in all:
      if word not in uni :
        uni.append(word)
    print(uni)
   for word in uni:
    c=all.count(word)
    count.extend([c,word])
    print(count)
    count.sort(reversed)
    for w in count:
       sorted.append(w(1))
    return sorted

f(s)
print(sorted)

You can use zip to pair the words the numbers and then sort it 您可以使用zip将数字配对,然后对其进行排序

>>> lst = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']
>>> [word.strip() for _,word in sorted(zip(lst[::2], lst[1::2]), reverse=True)]
['love', 'word', 'hello', 'you', 'hi']

To retain the order for words with same frequency, you have to zip with range as follows 要保留具有相同频率的单词的顺序,您必须按如下方式对range进行zip

>>> [w.strip() for *_,w in sorted(zip(lst[::2], range(len(lst)//2, 0, -1), lst[1::2]), reverse=True)]
['love', 'word', 'hello', 'hi', 'you']
x = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']
z = [w for _,w in sorted(zip(x[0::2],x[1::2]), reverse=True)]
print(z)
#[' love', ' word', 'hello', ' you', ' hi']

If the problem starts with s 如果问题以s开头

from collections import Counter
s="hello, word, word, love, love, love, hi, you"
slist = s.split(',')
sdict = dict(Counter(slist))
result = sorted(sdict.items(), key=lambda x: x[1], reverse=True)
result = [i[0] for i in result]
print(result) 
# [' love', ' word', 'hello', ' hi', ' you']

Your data structure is not good. 您的数据结构不好。 Don't put count and word in a flat list, but use tuples. 不要将计数和单词放在单个列表中,而是使用元组。 Otherwise, all numbers would be sorted independently from the words. 否则,所有数字将独立于单词排序。

reverse is a keyword-argument, which expects a boolean value. reverse是一个关键字参数,它需要一个布尔值。

def sort_words(text):
    words = text.split(',')
    unique_words = set(words)
    word_counts = []
    for word in unique_words:
        word_counts.append((words.count(word), word))
    word_counts.sort(reverse=True)
    sorted = []
    for count, word in word_counts:
        sorted.append(word)
    return sorted

Modify your code 修改你的代码

s="hello, word, word, love, love, love, hi, you"


def f(s):
    all= [v.strip() for v in s.split(',')]

    uni=[]
    count=[]
    sorted=[]
    for word in all:
        if word not in uni:
            uni.append(word)

    for word in uni:
        c = all.count(word)
        count.append([c, word])

    count.sort(key=lambda x: x[0], reverse=True)

    for w in count:
        sorted.append(w)
    return sorted

Recommend 推荐

from collections import Counter

def f(text):
    words = Counter([word.strip() for word in text.split(',')])
    return sorted(words, key=words.get, reverse=True)

Output 产量

['love', 'word', 'hello', 'hi', 'you']

I first thought about converting your list to a dictionary, but best would be to create a list of tuples. 我首先考虑将列表转换为字典,但最好是创建一个元组列表。 Obviously, the elements in the array seem sorted. 显然,数组中的元素似乎已经排序。 Then sort and reverse the order and yiu will get your list 然后排序并反转订单,yiu将获得您的列表

test = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']

new_test = [(test[x], test[x+1]) for x in range(0,len(test),2)]

new_test.sort()
new_test.reverse()
new_test

strings = []
for elem in new_test:
    strings.append(elem[1])
print(strings)

[' love', ' word', 'hello', ' you', ' hi']

Your answer is not pythonic. 你的答案不是pythonic。 If you have already counted the occurrences of the words, you may try 如果您已经计算了单词的出现次数,您可以尝试

aa = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']
cc = [v for c,v in sorted(zip(aa[0::2], aa[1::2]),reverse=True)]
print(cc)

If the input is a string as in your code, the following code works. 如果输入是代码中的字符串,则以下代码有效。


from collections import Counter
s="hello, word, word, love, love, love, hi, you"

cnt = Counter()
for w in s.split(','):
  cnt[w.strip()] += 1

print(sorted(cnt, key=cnt.get, reverse=True))

Thank @Pynchia. 谢谢@Pynchia。 Now the same thing can be achieved in two lines. 现在可以用两行来实现同样的目的。

from collections import Counter
cnt=Counter(s.replace(',', '').split()) 
print(sorted(cnt, key=cnt.get, reverse=True))

yet another solution, more idiomatic and a classic in grouping elements from an iterable 另一种解决方案,更具惯用性和经典的分组元素来自可迭代

x = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']
t = zip(*[iter(x)]*2)  # creates a seq of tuples with two consecutive elements each
s = sorted(t, reverse=True) # no need for a key
out = [e[1] for e in s]
print(out)

which gives 这使

[' love', ' word', 'hello', ' hi', ' you']

what about this beautiful solutions: 这个美丽的解决方案呢:

1) if you want to have your list: 1)如果你想要你的清单:

l = [1, 'hello', 2, ' word', 3, ' love', 1, ' hi', 1, ' you']
l[1::2] = [e.strip() for e in l[1::2]]
print([w for _, w in sorted(sorted(zip(l[::2], l[1::2])), key = lambda x: x[0], reverse=True)])

output: 输出:

 ['love', 'word', 'hello', 'hi', 'you']

2) if you want to start from s: 2)如果你想从s开始:

from collections import Counter

s = "hello, word, word, love, love, love, hi, you"

print([w for w, _ in sorted(sorted(Counter(s.split(', ')).items()), key=lambda x: x[1], reverse=True)])

output: 输出:

 ['love', 'word', 'hello', 'hi', 'you']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM