在python-lis中检查序列

2024-09-30 02:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表[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]


Tags: ids列表templistticketst1sortedprint
3条回答

下面是一个列表理解,可以让你得到你想要的:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
a = sorted_ids[0]
b = sorted_ids[-1]
nums = set(sorted_ids)
expected = ["T" + str(i) if i in nums else 'V' for i in range(a,b+1)]
print(expected)

输出:

^{pr2}$

下面是另一个值得考虑的解决方案:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]

for i in range(min(sorted_ids), max(sorted_ids)): 
     if sorted_ids[i] != i + 1: 
         sorted_ids.insert(i, 'V')

final_list = [ "T" + str(x) if isinstance(x, int) else x for x in sorted_ids]

结果:

^{pr2}$

这里有一个解决方案:

sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]

def arrange(inList):
    newList = []
    newList.append('T'+str(inList[0]))
    for i in range(1,len(inList)):
        diff = inList[i] - inList[i-1]
        if diff > 1:
            for d in range(diff-1):
                newList.append('V')
            newList.append('T'+str(inList[i]))
        else:
            newList.append('T'+str(inList[i]))
    return newList

print(arrange(sorted_ids))

输出:

^{pr2}$

相关问题 更多 >

    热门问题