如何一次浏览100个元素的列表



我得到了一个包含958个元素的列表。

myList = [1, 2, 3, 4, ..., 958]

我想取前100个元素,然后取下100个(从100到200(,以此类推

我尝试过的:

sum = 0
ct = 0
for i in range(len(myList):
sum = sum + myList[i]
ct = ct + 1
if ct == 100:
ct = 0 
print(sum)
sum = 0

它在第900个元素之前一直有效。然后它不能对myList的最后58个元素求和,因为ct不会得到100。

有什么想法吗?

一次遍历列表100,并对切片求和。超出列表末尾的切片处理正确:

myList = list(range(1,959))
for i in range(0,len(myList),100):
sub = myList[i:i+100]
print(f'sum of {sub[0]}..{sub[-1]} is {sum(sub)}')

输出:

sum of 1..100 is 5050
sum of 101..200 is 15050
sum of 201..300 is 25050
sum of 301..400 is 35050
sum of 401..500 is 45050
sum of 501..600 is 55050
sum of 601..700 is 65050
sum of 701..800 is 75050
sum of 801..900 is 85050
sum of 901..958 is 53911

因为只有当达到100的倍数时才打印总和,所以永远不会打印最后一组元素的总和,因为它不是100个元素。要获得最后一组,请在循环结束后打印总和。

您也可以使用enumerate()直接在循环中获取索引,而不是递增您自己的ct变量。

total = 0
for i, item in enumerate(myList, 1):
total += item
if i % 100 == 0:
print(total)
total = 0
# Print the final group
if i % 100 != 0:
print(total)

我还将sum变量重命名为total,因为sum是内置函数的名称。

来自itertools模块的文档:

from itertools import zip_longest

def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
# grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
# grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
args = [iter(iterable)] * n
if incomplete == 'fill':
return zip_longest(*args, fillvalue=fillvalue)
if incomplete == 'strict':
return zip(*args, strict=True)
if incomplete == 'ignore':
return zip(*args)
else:
raise ValueError('Expected fill, strict, or ignore')

for century in grouper(myList, 100, fillvalue=0):
print(sum(century))

您可以按如下方式对列表进行切片:

for k in range(0, len(mylist), 100):
print(sum(mylist[k:k+100]))

这将以100为一组打印元素的总和。如果列表长度不是100的精确倍数,则最后的总和将是剩余元素的总和

尝试以下操作:

index = 1
slicesize = 100
start = 0
end = 100
myList = range(1, 958)
while True:
myslice = myList[start:end]

index += 1
start = end
end = index * slicesize
if start > len(myList):
break

我认为这应该能奏效。

import random
# generate list with N elements, each of which is a random integer in [0, 99]
N = 57
random.seed()
myList = [random.randint(0, 99) for i in range(0, N)]
# Calculate total number of prints before there will be less than num_elem
# elements remaining in the list.
num_elem = 10
total_prints = len(myList) // num_elem
for i in range(0, total_prints):
index = i * num_elem
print(sum(myList[index:index + num_elem]))
# if there are remaining elements, print their sum
if (len(myList) % num_elem) != 0:
print(sum(myList[index + num_elem:]))
def n_elements_per_call(iterable, n=100):
buffer = []
for i in iterable:
buffer.append(i)
if len(buffer) < n:
continue
yield buffer
buffer.clear()
if buffer:
yield buffer
my_list = list(range(959))
for nums in n_elements_per_call(my_list):
print(nums)

最新更新