python - 在Python中迭代列表后,打印出余数

标签 python list

我有一个可能会更改的号码列表。我想把它切成 16 block ,这就是下面的效果,但除非能被 16 整除(不经常),否则我会得到剩菜。我想知道批量处理完后如何输出剩余的项目。

s = ["002","003","005","006","007","008","009","010","012","013","014","015","016","017","018","019","023","024","025","026","027","028","029","031","032","033","034","035","037","038","040","041","042","043","044","045","046","047","048","049","050","051","052","053","055","059","060","063","064","065","066","067","069","070","071","072","073","074","075","076","077","078","079","080","081","082","083","086","088","089","090","091","092","093","094","095","096","097","098","099","100","101","102","105","106","107","109","110","111","112","113","114","115","117","118","120","122","123","124","125","127","128","129","130","131","133","134","135","136","137","138","139","140","143","145","147","148","149","150","152","153","154","155","157","158","160","161","163","165","166","167","169","170","172","173","174","175","177","178","179","181","182","183","185","186","187","188","189","191","192","193","194","195","196","201","202","203","204","205","206","207","208","210","211","212","213","214","215","216","217","218","220","221","222","223","225","226","227","228","229","230","231","232","233","234","235","236","237","238","240","241","242","243","244","245","247","248","300","302"]

count = 0
store_count = []
for i in s:
    count += 1
    store_count.append(i)
    if count % 16 == 0 :
        print(store_count)
        store_count = []

输出如下所示:

['207', '208', '210', '211', '212', '213', '214', '215', '216', '217', '218', '220', '221', '222', '223', '225']
['226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '240', '241', '242']

最佳答案

循环结束后,检查store_count是否有商品:

for i in s:
    count += 1
    store_count.append(i)
    if count % 16 == 0 :
        print(store_count)
        store_count = []
if store_count:       # <---- Check leftover
    print(store_count) # <----

顺便说一句,您可以使用enumerate,而不是自己增加count :

store_count = []
for count, i in enumerate(s, 1):  # <----  `count` will be 1, 2, 3, ...
    store_count.append(i)
    if count % 16 == 0 :
        print(store_count)
        store_count = []
if store_count:
    print(store_count)

关于python - 在Python中迭代列表后,打印出余数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33183064/

相关文章:

python - 在 centos 6.7 上安装 booktype

python - 获取多个列表之间每列数据的平均值

Python clist 小部件不返回预期列表,仅返回每个项目的第一个字符

java - 如何将数组列表中的特定值添加到 HashMap 中?

c# - 在 C# 中比较两个列表

python - Supervisord、Flask、Tornado(退出状态 1;不是预期的)

python - 同一行中表格单元格的 XPath?

python - PyQt5 中的 devicePixelRatio 损坏

python - python 在数据框中每列中找到3个最大值并获取索引号

arrays - vb.net - 列表(字符串)排序,数字升序,字母降序