【发布时间】:2022-09-27 11:45:51
【问题描述】:
我会尽力解释。
说我有这个;它代表一个用户名(例如:jjo),一个可选的真实姓名(例如:josh),它后面总是跟一个“删除”。
list_of_people = [\'jjo\',\'josh\',\'remove\',\'flor30\',\'florentina\',\'remove\',\'mary_h\',\'remove\',\'jasoncel3\',\'jason celora\',\'remove\', \'lashit\', \'remove\']
我的目标是实现这一目标:
cut_list = [ [\'jjo\',\'josh\'], [\'flor30\', \'florentina\'], [\'mary_h\'], [\'jasoncel3\', \'jason celora\'], [\'lashit\']]
这里的问题是真实姓名是可选的,因此,它并不总是完美的“三重奏”。换句话说,我需要使用“删除”的存在作为一个支点来削减我的清单。
从口头上讲,我会说代码是:
如果遇到 \"remove\",请倒退并存储所有内容,直到遇到另一个 \"remove\"
一个问题是一开始没有“删除”(虽然我可以手动添加它),但我的主要问题是逻辑。我做错了。
这是迄今为止我的“最佳”镜头以及它给出的效果:
list_of_people = [\'jjo\',\'josh\',\'remove\',\'flor30\',\'florentina\',\'remove\',\'mary_h\',\'remove\',\'jasoncel3\',\'jason celora\',\'remove\', \'lashit\', \'remove\'] #Add the first 2 items #If \"remove\" is there (means there was no real name), remove it #Turn list into a list of lists cut_list = list_of_people[0:2] if \"remove\" in cut_list: cut_list.remove(\"remove\") cut_list = [cut_list] #Loop through and cut based on the presence of \"remove\" for i in range(2, len(list_of_people)): if list_of_people[i] == \'remove\': first_back = list_of_people[i-1] if list_of_people.append(list_of_people[i-2]) != \'remove\': second_back = list_of_people[i-2] cut_list.append([first_back, second_back]) print(cut_list) # #Should give: # ##cut_list = [ [\'jjo\',\'josh\'], [\'flor30\', \'florentina\'], [\'mary_h\'], [\'jasoncel3\', \'jason celora\'], [\'lashit\']][[\'jjo\',\'josh\'],[\'josh\',\'jjo\'],[\'josh\',\'jjo\'],[\'josh\', \'jjo\'], [\'florentina\', \'flor30\'], [\'florentina\', \'flor30\'], [\'mary_h\', \'remove\'], [\'mary_h\', \'remove\'], [\'mary_h\', \'remove\'], [\'jason celora\', \'jasoncel3\'], [\'jason celora\', \'jasoncel3\'], [\'lashit\', \'消除\']]