简体   繁体   English

将嵌套循环转换为列表理解

[英]Convert nested loop to list comprehension

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. 我有点怀疑这是不可能的,因为我追加result不是在内循环中,而是在外循环中,但是我可能是错的。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM