Reputation: 155
I have an iteration over a dataframe, but for the example here I used a list.
seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []
for i in range(1, len(seq)):
if seq[i] > seq[i-1]:
box.append(seq[i])
else:
box.append(seq[i-1]+10)
box
Now i would like to add to each appended value a string prefix like this:
For all values from the If statement letter 'A-'
For all values from else statement letter 'B-'
My desired output is:
[B-10, A-0, A-1, A-2, B-12, B-11, B-10......
I tried it with .join and with simple comma or + inside the append method, but none of it works. Any suggestions how to accomplish this ?
Upvotes: 0
Views: 128
Reputation: 351
Idiotic one-liner:
box = map(lambda p: "A-" + str(p[1]) if p[1] > p[0] else "B-" + str(p[0] + 10), [(seq[i-1], seq[i]) for i,_ in enumerate(seq[:])][1:])
But in all seriousness just use string concatenation, but convert the integer value to string before concatenating:
seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []
for i in range(1, len(seq)):
if seq[i] > seq[i-1]:
box.append("A-" + str(seq[i]))
else:
box.append("B-" + str(seq[i-1]+10))
print (box)
Upvotes: 0
Reputation: 1874
You can use the f-string
literal to add the related letter:
seq = [0, -1, 0, 1, 2, 1, 0, -1, -2, -3, -4, -5, -4, -3, -2, -1]
box = []
for i in range(1, len(seq)):
if seq[i] > seq[i-1]:
box.append(f"A-{seq[i]}")
else:
box.append(f"B-{seq[i-1]+10}")
print(box)
OUT: ['B-10', 'A-0', 'A-1', 'A-2', 'B-12', 'B-11', 'B-10', 'B-9', 'B-8', 'B-7', 'B-6', 'A--4', 'A--3', 'A--2', 'A--1']
Upvotes: 3