I'm trying to convert a list of tuples to a list of strings by joining the tuple elements to a string. The problem is that some tuple values are not strings, so I have to convert them. I have successfully solved this problem with a nested loop. However, I can't seem to be able to come up with an equivalent list comprehension.
Here's my solution. I start with these values:
values = [(1, '2', 'X'), (2, '4', 'Y'), (7, '5', 'Z')]
The result should look like this:
result = ['1_2_X', '2_4_Y', '7_5_Z']
And here's my solution using nested loops:
values = [(1, '2', 'X'), (2, '4', 'Y'), (7, '5', 'Z')]
result = []
for v in values:
new_v = []
for s in v:
new_v.append(str(s))
result.append("_".join(new_v))
Is there an equivalent list comprehension or is this not possible? I kind of suspect that it is not possible because I append to result not in the inner loop, but in the outer loop, but I might be wrong.
As a bonus, maybe I'm overthinking this and there is a much simpler solution for what I want to achieve.
output = ['_'.join(map(str, x)) for x in values]