Create list dependent on another list

I have a list containing ages of transfers in football. The transfer changes from transfer into the club and out of the club every time "Age" is present in the list.

Therefore I want to create a new list with "in" and "out" elements to label to transfer.

ages = ["Age", "23", "20", "18", "Age", "23", "14", "Age", "35", "32", "24", "Age", "35"]

Expected output:

in_out = ["Age", "in", "in", "in", "Age", "out", "out", "Age", "in", "in", "in", "Age", "out"]

Any help is highly appreciated!

Upvotes: 0

Views: 56

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

you can try this:

ages = ["Age", "23", "20", "18", "Age", "23", "14", "Age", "35", "32", "24", "Age", "35"]

s = ["in", "out"]
out = []
j = 1
for i in ages:
    if i=="Age":
        out.append("Age")
        j = ~j
    else:
        out.append(s[j])

Output:

['Age',
 'in',
 'in',
 'in',
 'Age',
 'out',
 'out',
 'Age',
 'in',
 'in',
 'in',
 'Age',
 'out']

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

You could try with a one-liner list comprehension:

print([['out', 'in'][ages[:i].count('Age') % 2] if v != 'Age' else v for i, v in enumerate(ages)])

Or you could try with a for loop:

ages = ["Age", "23", "20", "18", "Age", "23", "14", "Age", "35", "32", "24", "Age", "35"]
x = 'out'
for i, v in enumerate(ages):
    if v == 'Age':
        x = ['in', 'out'][x == 'in']
    else:
        ages[i] = x

print(ages)

Both output:

['Age', 'in', 'in', 'in', 'Age', 'out', 'out', 'Age', 'in', 'in', 'in', 'Age', 'out']

Upvotes: 1

Related Questions