如何每隔n个项目拆分一个列表

我试图每隔 5 个项目拆分一个列表,然后删除接下来的两个项目('nan')。我曾尝试使用 List[:5],但这似乎无法循环使用。所需的输出是:[['1','2','3','4','5'],['1','2','3','4','5'], ['1','2','3','4','5'],['1','2','3','4','5']]


List = ['1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan']


for i in List:

    # split first 5 items

    # delete next two items


# Desired output:

# [['1','2','3','4','5'],['1','2','3','4','5'],['1','2','3','4','5'],['1','2','3','4','5']]


明月笑刀无情
浏览 112回答 4
4回答

侃侃尔雅

有很多方法可以做到这一点。我建议步进 7 然后拼接 5。data = ['1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan']# Step by 7 and keep the first 5chunks = [data[i:i+5] for i in range(0, len(data), 7)]print(*chunks, sep='\n')输出:['1', '2', '3', '4', '5']['1', '2', '3', '4', '5']['1', '2', '3', '4', '5']['1', '2', '3', '4', '5']

白衣非少年

警告:确保列表遵循您所说的规则,每 5 项 2 nan 之后。此循环会将前 5 个项目添加为列表,并删除前 7 个项目。lst = ['1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan','1','2','3','4','5','nan','nan']output = []while True:&nbsp; &nbsp; if len(lst) <= 0:&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; output.append(lst[:5])&nbsp; &nbsp; del lst[:7]print(output) # [['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']]

森栏

我喜欢拼接的答案。这是我的 2 美分。# changed var name away from var typemyList = ['1','2','3','4','5','nan','nan','1','2','3','4','10','nan','nan','1','2','3','4','15','nan','nan','1','2','3','4','20','nan','nan']newList = []&nbsp; &nbsp;# declare new list of lists to createaddItem = []&nbsp; &nbsp;# declare temp listmyIndex = 0&nbsp; &nbsp; # declare temp counting variablefor i in myList:&nbsp; &nbsp; myIndex +=1&nbsp; &nbsp; if myIndex==6:&nbsp; &nbsp; &nbsp; &nbsp; nothing = 0&nbsp; #do nothing&nbsp; &nbsp; elif myIndex==7: #add sub list to new list and reset variables&nbsp; &nbsp; &nbsp; &nbsp; if len(addItem)>0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newList.append(list(addItem))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; addItem=[]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myIndex = 0&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp;addItem.append(i)#outputprint(newList)

qq_花开花谢_0

如果列表不遵循您提到的规则但您希望始终在 NAN 之间拆分序列,则直接解决方案:result, temp = [], []for item in lst:&nbsp; &nbsp; if item != 'nan':&nbsp; &nbsp; &nbsp; &nbsp; temp.append(item)&nbsp; &nbsp; elif temp:&nbsp; &nbsp; &nbsp; &nbsp; result.append(list(temp))&nbsp; &nbsp; &nbsp; &nbsp; temp = []
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python