【发布时间】: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