python - 如何在循环遍历一定数量的元素后创建另一个元素?

标签 python list

我将输入列表的长度添加到具有字符串格式的参数中:

input_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
freq_list = "freq=[{}]".format(len(input_list))
print(freq_list)

当我尝试打印字符串时,它显示 'freq=[13]',这表明 input_list 的长度是 13,这很好本身。但是,如果我希望在循环遍历数据列表时每 10 个元素创建一个新元素怎么办?

在这个长度为 13 的情况下,如何获得 'freq=[10, 3]' 而不是 'freq=[13]'

更多例子:

  • 如果长度为11:'freq=[10, 1]'
  • 如果长度为24:'freq=[10, 10, 4]'

最佳答案

这里不需要循环,可以用简单的算法算出长度中有多少个10。您想要将长度除以 10(使用 // floor division operator )以获得十位数,并使用 % modulo operator获得除法余数:

length = len(input_list)
tens, remainder = length // 10, length % 10
freq_list = "freq={}".format([10] * tens + ([remainder] if remainder else []))

请注意,我格式化了由单独的 [10][remainder] 组件构成的整个列表。具有整数的列表对象的表示完全符合您指定的输出,每个逗号后有一个空格:

>>> length = 11
>>> tens, remainder = length // 10, length % 10
>>> "freq={}".format([10] * tens + ([remainder] if remainder else []))
'freq=[10, 1]'
>>> length = 24
>>> tens, remainder = length // 10, length % 10
>>> "freq={}".format([10] * tens + ([remainder] if remainder else []))
'freq=[10, 10, 4]'

如果长度是 10 的倍数,则剩余部分将被删除,您只会得到 10 值:

>>> length = 20
>>> tens, remainder = length // 10, length % 10
>>> "freq={}".format([10] * tens + ([remainder] if remainder else []))
'freq=[10, 10]'

关于python - 如何在循环遍历一定数量的元素后创建另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934020/

相关文章:

python - 在不下载文件的情况下在网站上查找音频文件的比特率

python - for循环在python中包含或排他

python - 引用列表位置

javascript - Javascript 数组中的 indexOF 方法

python - 优化两个列表之间的比较,给出不同的索引

python - 连接到 dask.distributed 集群时出现 Pickle 错误

python - 在 Python-Scrapy 中执行 Js 的 Selenium 替代品是什么?

python - 如何在 Pandas 中找到数字列?

java - 从单个列表创建多个列表的算法

python - 在列表中重复列表 X 次