Home > Mobile >  add select values in a tuple with python
add select values in a tuple with python

Time:07-12

does anyone know why that error comes out when trying to add four positions in a variable? I have tried with only one position and it works for me, but if I try to add more it gives me an error:

My error:

Traceback (most recent call last):
  File "\script.py", line 165, in <module>
    Ad100()
  File "\script.py", line 142, in Ad100
    baseAd100.extend(row[0,2,3,4])
TypeError: tuple indices must be integers or slices, not tuple

My code:

def Ad100():
    for rows in pcorte:  ##pcorte es el resultado de una consulta.
        print(rows)
    
    baseAd100 = []
    
    for row in pcorte:
##        llenado.append(row[0]) this way works for me in another function with only the first position
        baseAd100.extend(row[0,2,3,4]) ##in this way it generates an error

    print(baseAd100)

My data:

('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)

CodePudding user response:

List/tuple indexing doesn't work that with with comma-separated values. You either get one item (row[1]) or a slice of items, e.g. row[1:4] gets items 1 up to but not including 4. See slice() for more details.

There is a method to get non-contiguous indices however:

from operator import itemgetter

baseAd100 = []
row = ('220002393681', '0171', '823', 'S', 1008, '25175', 997, 547)

baseAd100.extend(itemgetter(0,2,3,4)(row))
print(baseAd100)

Output:

['220002393681', '823', 'S', 1008]

itemgetter(0,2,3,4) generates a function that will extract the specified indices from the argument, then it is passed the row.

CodePudding user response:

thanks @Pranav Hosagadi guide me with your comment, it's not the best, but that's how my code looks

def Ad100():    
    baseAd100 = []    

    for row in val:
        baseAd100.append(str(row[0]) ","   str(row[2:4]))        
    print(baseAd100)
  • Related