我有一个包含大量数据的大型列表,这些数据是从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
答案 0 :(得分:10)
total_avg = sum( map(len, strings) ) / len(strings)
代码中的问题出在以下代码行中:
total_size = sum(all_lengths)
没有必要在循环的每个循环中计算这个。
循环后更好地完成这个。
答案 1 :(得分: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)
答案 2 :(得分: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,
)
答案 3 :(得分:0)
只使用均值和理解:
holder.view.setOnClickListener{
val curValue = holder.adapterPosition
val selectedValue = stations[curValue].name
//something should be done here to change button's color
(context as MainActivity).updateButtonColor(HEX_COLOR)
}
答案 4 :(得分: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)))
答案 5 :(得分: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