Home > Software design >  Delete item from list of tuples and move items up
Delete item from list of tuples and move items up

Time:08-08

I want to delete an element from a list of tuples and move the other items that had the same position.

Input:

a=[('201001', '-4'), ('201002', '2'), ('201003', '6')]

Desired output:

a=[('201001', '2'), ('201002', '6'), ('201003', 'na')]

I have tried the following code for it:

a[0](:- 1)

But I get SyntaxError: invalid syntax

I would appreciate it if you could suggest ways to solve this case.

CodePudding user response:

Iterate through each element and set the tuple so that the second value is the value of the next element (except the last element because there is no element after it)

for i, val in enumerate(a):
    try:
        a[i] = (val[0], a[i 1][1])
    except IndexError:
        a[i] = (val[0], "na")

instead of error catching, you could also use the index:

arr_len = len(a) - 1
for i, val in enumerate(a):
    if i == arr_len:
        a[i] = (val[0], "na")
        break
    a[i] = (val[0], a[i 1][1])

CodePudding user response:

Another way using zip:

a = [('201001', '-4'), ('201002', '2'), ('201003', '6')]

output = [(x, y) for (x, _), (_ ,y) in zip(a, [*a[1:], (None, 'na')])]

print(output) # [('201001', '2'), ('201002', '6'), ('201003', 'na')]

CodePudding user response:

Here's a different way that lets you choose where you want to delete your number:

a = [('201001', '-4'), ('201002', '2'), ('201003', '6'), ('201004', '8'), ('201005', '3')]

def delete_item(position, arr):  # position starting at 0, [(0,0), (1,1), (2,2), etc]
    newNums = ([arr[x][1] for x in range(0, position)] 
                 [arr[x][1] for x in range(position 1, len(arr))] 
                 ['na'])
    arr = [(arr[x][0], y) for x,y in zip(range(len(arr)), newNums)]
    return arr
    
newTuple = delete_item(3, a)

Ouput:

[('201001', '-4'),
 ('201002', '2'),
 ('201003', '6'),
 ('201004', '3'),
 ('201005', 'na')]

Then you can keep putting the list of tuples in to remove a new number at a new position:

newTuple = delete_item(1, newTuple)

Output:

[('201001', '-4'),
 ('201002', '6'),
 ('201003', '3'),
 ('201004', 'na'),
 ('201005', 'na')]
  • Related