如何在没有 len() 的情况下对列表中的项目进行操作?
How to handle operating on items in a list without perfectly even len()?
我正在尝试对列表中的每 5 个项目进行操作,但无法弄清楚如果剩余的项目没有平均分为 5 个如何处理。现在我正在使用模数,但是我无法摆脱这不是正确答案的感觉。这是一个例子...
list = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
i = 0
for o in list:
i += 1
newlist.append(o)
if i % 5 == 0:
for obj in newlist:
function_for(obj)
newlist.clear()
此代码将执行 function_for() 两次,但不会执行第三次以处理剩余的 4 个值。如果我添加一条 'else' 语句,它会在每次执行时运行。
处理这种情况的正确方法是什么?
这种方法很简单,如果你不介意修改列表:
mylist = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
while mylist:
function_for( mylist[:5] )
mylist = mylist[5:]
您还可以检查索引是否等于列表的长度。 (此外,在这里使用 enumerate
而不是计数器变量更为惯用。)
lst = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
for i, o in enumerate(lst, 1):
newlist.append(o)
if i % 5 == 0 or i == len(lst):
print(newlist)
newlist.clear()
我正在尝试对列表中的每 5 个项目进行操作,但无法弄清楚如果剩余的项目没有平均分为 5 个如何处理。现在我正在使用模数,但是我无法摆脱这不是正确答案的感觉。这是一个例子...
list = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
i = 0
for o in list:
i += 1
newlist.append(o)
if i % 5 == 0:
for obj in newlist:
function_for(obj)
newlist.clear()
此代码将执行 function_for() 两次,但不会执行第三次以处理剩余的 4 个值。如果我添加一条 'else' 语句,它会在每次执行时运行。
处理这种情况的正确方法是什么?
这种方法很简单,如果你不介意修改列表:
mylist = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
while mylist:
function_for( mylist[:5] )
mylist = mylist[5:]
您还可以检查索引是否等于列表的长度。 (此外,在这里使用 enumerate
而不是计数器变量更为惯用。)
lst = ["ValA","ValB","ValC","ValD","ValE","ValF","ValG","ValH","ValI","ValJ","ValK","ValL","ValM","ValN",]
newlist = []
for i, o in enumerate(lst, 1):
newlist.append(o)
if i % 5 == 0 or i == len(lst):
print(newlist)
newlist.clear()