A =["I like apple"]
B =["I like playing basketball"]
C =["how are you doing"]
listt=[A,B,C]
我需要返回列表中包含最多单词的字符串(在此示例中为B和C)。
首先,我想计算每个字符串中的单词数,但我的代码不起作用。有谁知道如何返回单词最多的字符串?
number = len(re.findall(r'\w+',listt))
使用max
:
print(max(A+B+C,key=lambda x: len(x.split())))
如果想同时显示:
print([i for i in A+B+C if i == max(A+B+C,key=lambda x: len(x.split()))])
试试这个:
[len(i[0].split(' ')) for i in listt]
你可以只是.count
空间(分隔单词):[s for s in sentences if s.count(' ') == max(s.count(' ') for s in sentences)]
(s[0]
,如果你有一个单独的列表中的每个句子,可能首先得到max
以节省时间)
如果您的单词也可以用任何标点符号分隔,您可能会想要使用re
,就像在您的示例中一样,只需对每个句子进行findall
ing,如下所示:
import re
pattern = re.compile(r'\w+')
# note I changed some stuff to have words only separated by punctuation
sentences = [["I like:apple"], ["I (really)like playing basketball"], ["how are you doing"]]
current_s = []
current_len = 0
for s in sentences:
no = len(pattern.findall(s[0])) # [0] because you have each sentence in a separate list
if no == current_len:
current_s.append(s)
elif no > current_len:
current_s = [s]
current_len = no
print('the most number of words is', current_len)
print('\n'.join(current_s))
按句号拆分句子和顺序:
A = ["I like apple"]
B = ["I like playing basketball"]
C = ["how are you doing today?"]
sorted_sentences = sorted([(sentence, len(sentence[0].split(' '))) for sentence in [A, B, C]], key=lambda x: x[1],
reverse=True)
print('The sentence: "{}" has the maximum number of words: {}'.format(sorted_sentences[0][0],sorted_sentences[0][1]))
产量
The sentence: "['how are you doing today?']" has the maximum number of words: 5
经过研究,我发现这使用max
功能。使用max函数计算最大单词数,然后打印单词最多的单词。
A ="I like apple"
B ="I like playing basketball"
C ="how are you doing"
sentences=[A,B,C]
max_words=max(len(x.split(' ')) for x in sentences)
print([i for i in sentences if len(i.split(' '))==max_words])
python的基本逻辑,没有任何特殊功能:
A ="I like apple"
B ="I like playing basketball"
C ="how are you doing"
sentences=[A,B,C]
max_words=0
for sentence in sentences:
if len(sentence.split(' '))>max_words:
max_words=len(sentence.split(' '))
for sentence in sentences:
if len(sentence.split(' '))==max_words:
print (sentence)
print(max_sentences)
A = ["I like apple"]
B = ["I like playing basketball"]
C = ["how are you doing"]
items = A + B + C
longest_length = len(max(items, key=lambda k: len(k.split())).split())
result = [i for i in items if len(i.split()) == longest_length]
print(result)
输出:
['I like playing basketball', 'how are you doing']
请注意max函数而不是字符串的长度:
max()方法返回字符串str中的最大字母字符。
这就是为什么我使用键lambda函数将默认比较更改为字符串key=lambda k: len(k.split())
中的单词数