在列表中查找字符串的平均长度

5

我有一个大型列表,其中包含许多从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。

2
那问题出在哪里? - Maroun
你需要的是 average(map(len,list1)) 吗? - The6thSense
@kojiro 使用 Python 2.7,不确定在 Python 3 中如何运行。 - The6thSense
@VigneshKalai Python 2.7没有名为“average”的全局关键字。你在使用哪个库? - kojiro
我不是Python专家,但我怀疑建立一个长整数列表来计算它们的平均值并不是最有效的方法。你不能只是在一个变量中累加长度,然后除以列表的长度吗? - Renaud Pacalet
显示剩余5条评论
6个回答

15
total_avg = sum( map(len, strings) ) / len(strings)

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


我认为你想要写的是 len(strings) 而不是 total_size - interjay
@interjay 当然可以。我认为问题的作者定义了这个变量。 - ig-melnyk

2

只需使用mean和一个理解:

     from statistics import mean

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

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


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)

0
我猜你可以在循环中将字符串连接成一个大字符串,以检查所有项的长度。
list1 = ['foo', 'bar', 'bob', 'jess', 'google', 'alphabet']

combined_string = ''
for item in list1:
    combined_string += item

print(float(len(combined_string)) / float(len(list1)))

0

在循环的每个点上同时计算平均值和总数非常容易,这样你就可以展示进度了:

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,
    )

0

使用纯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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接