【问题标题】:How to get the mean of each index in a list and take the ones that are bigger than average?如何获取列表中每个索引的平均值并取大于平均值的索引?
【发布时间】:2020-02-07 12:39:19
【问题描述】:

我有这个列表叫你好:

['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']

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

【问题讨论】:

  • 不清楚你在问什么,举个例子你想做什么

标签: python python-3.x list indexing


【解决方案1】:

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

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

请注意,/ 运算符返回一个浮点数,您可能希望根据自己的偏好对其进行四舍五入。

【讨论】:

    【解决方案2】:

    您可以使用列表推导列出每个长度的长度,然后得到它的总和,然后除以长度:

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

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

    sentences = [sentence for sentence in sentences if len(sentence) > average]
    

    【讨论】:

      【解决方案3】:

      尝试仅列出长度大于原始列表中平均句子长度的句子的新列表

      new_sentence_list = []
      for i in original_sentence_list:
         if len(i) > mean(len(i) for i in original_sentence_list):
           new_sentence_list.append(i)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-09
        • 2019-02-01
        • 2019-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        相关资源
        最近更新 更多