我有一个列表[T20,T5,T10,T1,T2,T8,T16,T17,T9,T4,T12,T13,T18]
我去掉了T,转换成整数类型,并对列表进行了排序,得到:
排序后的用户名=[1,2,4,5,8,9,10,12,13,16,17,18,20]
我在列表上循环,检查下一个数字到当前数字是否在数字序列中。如果没有,我想在它的位置插入一个“V”。在
最终看起来应该是
但是,我不能在正确的位置插入V的确切编号。在
def arrange_tickets(tickets_list):
ids=[]
for item in tickets_list:
new_str=item.strip("T")
ids.append(int(new_str))
sorted_ids = sorted(ids)
temp_ids = []
print("Sorted: ",sorted_ids)
#size = len(sorted_ids)
for i in range(len(sorted_ids)-1):
temp_ids.append(sorted_ids[i])
if sorted_ids[i]+1 != sorted_ids[i+1] :
temp_ids.insert(i+1,"V")
print(temp_ids)
#print(sorted_ids)
tickets_list = ['T20', 'T5', 'T10', 'T1', 'T2', 'T8', 'T16', 'T17', 'T9', 'T4', 'T12', 'T13', 'T18']
print("Ticket ids of all the available students :")
print(tickets_list)
result=arrange_tickets(tickets_list)
Actual Result: [1, 2, 'V', 4, 'V', 5, 8, 'V', 9, 'V', 10, 12, 'V', 13, 16, 17, 18]
Expected Result: [T1, T2, V, T4, T5, V, V, T8, T9, T10, V, T12, T13, V, V, T16, T17, T18, V, T20]
下面是一个列表理解,可以让你得到你想要的:
输出:
^{pr2}$下面是另一个值得考虑的解决方案:
结果:
^{pr2}$这里有一个解决方案:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐