1

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.

9
  • 3
    output = ['_'.join(map(str, x)) for x in values] Commented Sep 14, 2018 at 12:06
  • 1
    output = ["_".join([str(x) for x in i]) for i in values] Commented Sep 14, 2018 at 12:08
  • Wow, thanks for all these quick and great answers! Now since all answers are correct, which one should I accept? Commented Sep 14, 2018 at 12:16
  • @cbrnr You accept the one you are going to use. And if you in the future use another you should change to that (theoretically). That's my idea. Commented Sep 14, 2018 at 12:17
  • 1
    Thanks @strava, I also thought that her/his answer is very slightly more readable, but you were faster. Both of you should get credit. Commented Sep 14, 2018 at 12:31

3 Answers 3

1
result = ['_'.join(str(token) for token in value) for value in values]
Sign up to request clarification or add additional context in comments.

Comments

1
['_'.join((str(s) for s in seq)) for seq in values]

Comments

0

Another take:

result = ['{}_{}_{}'.format(*i) for i in values]

7 Comments

similar to other solutions but less generic
@Shiva no it works, but assumes that there are always 3 items per tuple
@Shiva ofc it will :). I like options. I think it is very readable depending on what you do.
This didn't work for me, because it produced ['1___2', '2___4', '7___5']. However, this modification makes it work: ['{}_{}_{}'.format(*i.split("_")) for i in values].
@cbrnr hmm... dunno, did you use your right dataset?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.