-2

Hi guys I'm having the current problem:

list_a = [('abc d',1), ('abc d',2) ,('acb e',3) ,('b',1),('b',2),('b',3)]

from list_a, I am trying to build a function that would return the following output...

Essentially I want to keep all [0] values that start with the string 'a' and make modifications to its respective [1]'s.

The modification being a simple [1] x 2 ...

('abc d',1) --> ('abc d',2)
('abc d',2) --> ('abc d',4)
('act d',3) --> ('abc d',6)

Keeping the other pairs as they were since they start off with a 'b' in the [0] position.

Desired Output:

[('abc d',2), ('abc d',4) ,('acb e',6) ,('b',1),('b',2),('b',3)]

Thank you in advance :)

Axe319
  • 4,255
  • 3
  • 15
  • 31
  • 1
    What have you tried so far and what specific part are you having trouble with? – Axe319 Mar 18 '20 at 15:29
  • Hi Axe319, thanks for asking. I tried to unpack them first, then zip them again in the right order. But this process would work in other iterative process in the code I am currently. working on :( – antoniosalomao Mar 18 '20 at 15:30
  • So, multiply `x[1]` by 2 if `x[0]` starts with `a`? – chepner Mar 18 '20 at 15:30
  • "make modifications to its respective [1]'s." Do you want to *change* the tuples, or are you fine creating new tuples? – MisterMiyagi Mar 18 '20 at 15:39

2 Answers2

2

Just use list comprehension

list_b = [(i[0],i[1] * 2) if i[0].startswith("a") else i for i in list_a ]
tomgalpin
  • 1,943
  • 1
  • 4
  • 12
0

You can do it in the following way.

list_a = [('abc d',1), ('abc d',2) ,('acb e',3) ,('b',1),('b',2),('b',3)]

def foo(list_a):
    output=[]
    for x,y in list_a:
        if x[0] =="a":
            output.append((x,2*y))
        else:
            output.append((x,y))
    return output
McLovin
  • 555
  • 8
  • 20