【问题标题】:Finding average length of strings in a list查找列表中字符串的平均长度
【发布时间】:2015-09-03 13:22:55
【问题描述】:

我有一个大列表,其中包含从 csv 文件中读取的大量数据。 为简单起见,我将为您提供一个虚拟列表,其中包含的数据要少得多。

list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']

我想找到列表中字符串的平均长度。我目前正在这样做:

all_lengths = []
num_of_strings = len(list1)

for item in list1:
    string_size = len(item)
    all_lengths.append(string_size)
    total_size = sum(all_lengths)
ave_size = float(total_size) / float(num_of_strings)

问题在于,由于实际列表非常大,因此执行此操作需要非常长的时间。

是否有更优化或更优雅的方式来执行此操作。

另外,为了它的价值,使用 Python2.7

【问题讨论】:

  • 有什么问题?
  • 我看不到all_lengths 的更新位置,你确定你不应该对all_sizes 求和,为什么还要在循环之外求和?
  • 你得到了什么输出
  • 这就是你想要的average(map(len,list1))
  • @VigneshKalai 最好指出 average 来自 Python 3.4 及更高版本中的 statistics 模块。

标签: python list python-2.7


【解决方案1】:
total_avg = sum( map(len, strings) ) / len(strings)

您的代码中的问题在于这行代码: total_size = sum(all_lengths) 无需在循环的每个循环中计算此值。 最好在循环后做这个。

【讨论】:

  • 我想你的意思是写len(strings)而不是total_size
  • @interjay 是的,当然。我认为问题的作者定义了这个变量。
【解决方案2】:

我能想到的最简单的方法是:

list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']
total = 0
for i in list1:
    total += len(i)
ave_size = float(total) / float(len(list1))
print(ave_size)

【讨论】:

    【解决方案3】:

    只需使用均值和理解:

         from statistics import mean
    
         list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']
         print(mean([len(i) for i in list1]))
         >>> 4.5
    

    【讨论】:

      【解决方案4】:

      在循环中的每个点同时计算平均值和总数是相当容易的,因此您也可以显示进度:

      total = 0
      items = 0
      average = 0.
      for item in very_long_list:
          items += 1
          total += len(item)
          average = float(total) / items
          print 'Processed items: %d with a total of %d and an average length of %.1f' % (
              items,
              total,
              average,
          )
      

      【讨论】:

        【解决方案5】:

        我猜你可以将循环中的字符串连接成一个大字符串来检查所有项目的长度。

        list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']
        
        combined_string = ''
        for item in list1:
            combined_string += item
        
        print(float(len(combined_string)) / float(len(list1)))
        

        【讨论】:

          【解决方案6】:

          使用纯 Python 和列表推导:

          list_of_strings = ["My cat ran across the street",
                             "I love my blue shirt",
                             "Sir, would you like another coffee?",
                             "Mountain",
                             "Car",
                             "I wish in school there had been a class where all you do is solve puzzles the entire class. Instead of taking trigonometry, which I 100% forget."]
          
          # Average length of strings
          avg_string_length = sum([len(i) for i in list_of_strings])/len(list_of_strings)
          avg_string_length
          
          >>> 39.666666666666664
          
          # Round it out
          round(avg_string_length)
          
          >>> 40
          

          【讨论】:

            猜你喜欢
            • 2018-01-20
            • 2023-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-03-29
            • 2011-10-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多