嗨,我有一个2d列表,有3个元素 我使用以下代码连接了一些元素
list1 = [(1,"hello",3),(1,"excelent",4),(2,"marvelous",3)]
length = len(list1)
text = ''
for irow in range(length):
number = list1[irow][0]
listText = list1[irow][1]
ids = list1[irow][2]
text += "<tag id = "+ str(ids)+">"+str(listText)+"<\\tag>\r\n"
print(text)
这将产生以下输出
<tag id = 3>hello<\tag>
<tag id = 4>excelent<\tag>
<tag id =3>marvelous<\tag>
这是正确的,我的问题是,有没有一种方法可以通过列表理解来做到这一点,或者有没有一种更为通灵的方法来实现同样的结果
您可以将整个过程简化为一行,但我建议合理的折衷方法可能仍然是在列表上使用
for
循环,但在for
循环目标中,您可以将子列表直接解压缩到相关变量中。在任何情况下,都不需要在索引上循环,而需要在list1
的实际内容上循环。使用f-string(在最近的Python版本中)也有助于整理东西您也可以考虑使用常规的哑变量{}代替^ {< CD5>},因为您实际上没有使用值:
使用列表理解:
输出:
编辑:
如果要在标记文本中使用双引号:
输出:
使用f字符串并在列表理解中解包元组元素可以使其清晰可读:
相关问题 更多 >
编程相关推荐