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.
['_'.join((str(s) for s in seq)) for seq in values]
result = ['_'.join(str(token) for token in value) for value in values]
另取:
result = ['{}_{}_{}'.format(*i) for i in values]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.