如何获取列表中每个索引的平均值,并取大于平均值的索引?

问题描述 投票:0回答:2

我有这个列表叫你好:

['Apple is one of the most healthy fruits ever - it grows in many countries',
 'Jenny likes strawberry',
 'He had an accident in New York Downtown',
 'One of the safest cities is the city Tokyo in Japan',
 'Some drugs are better than others',
 'Ice-cream is famous, Italian ice-cream is the most famous',
 'German cars are known to be the best cars']

我想获得这些句子的平均字符,并取出比te average长的句子。我该怎么做?

python python-3.x list indexing
2个回答
2
投票

您可以使用sum()并为此进行列表理解

avg_len = sum(len(str) for str in strings) / len(strings)
filtered = [str for str in strings if len(str) >= avg_len]

注意/运算符返回一个浮点,并且您可能想根据自己的喜好舍入它。


0
投票

您可以使用列表推导来列出每个长度的长度,然后获取其总和并将其除以长度:

average = sum([len(x) for x in sentences])/len(sentences)

然后您可以遍历列表并删除超过该限制的句子

for sentence in enumerate(sentences):
    if sentence[1] > average:
        sentences.pop(sentence[0])

我希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.