用列表理解而不是for循环连接二维列表

2024-10-03 02:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个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>

这是正确的,我的问题是,有没有一种方法可以通过列表理解来做到这一点,或者有没有一种更为通灵的方法来实现同样的结果


Tags: 方法textidids元素hello列表tag
3条回答

您可以将整个过程简化为一行,但我建议合理的折衷方法可能仍然是在列表上使用for循环,但在for循环目标中,您可以将子列表直接解压缩到相关变量中。在任何情况下,都不需要在索引上循环,而需要在list1的实际内容上循环。使用f-string(在最近的Python版本中)也有助于整理东西

list1 = [(1,"hello",3),(1,"excelent",4),(2,"marvelous",3)]

text = ''
for number, listText, ids in list1:
    text += f'<tag id = {ids}>{listText}<\\tag>\r\n'

print(text)

您也可以考虑使用常规的哑变量{}代替^ {< CD5>},因为您实际上没有使用值:

for _, listText, ids in list1:

使用列表理解:

ee = [(1,"hello",3),(1,"excelent",4),(2,"marvelous",3)]
  
print(["<tag id = "+ str(x[2])+">"+str(x[1])+"<\tag>" for x in ee])

输出:

['<tag id = 3>hello<\tag>', '<tag id = 4>excelent<\tag>', '<tag id = 3>marvelous<\tag>']  

编辑:

如果要在标记文本中使用双引号:

print(["<tag id = " + str(x[2])+" >" + str('"' + x[1] + '"') + "<\tag>" for x in ee])

输出:

['<tag id = 3 >"hello"<\tag>', '<tag id = 4 >"excelent"<\tag>', '<tag id = 3 >"marvelous"<\tag>'] 

使用f字符串并在列表理解中解包元组元素可以使其清晰可读:

list1 = [
    (1, "hello", 3),
    (1, "excelent", 4),
    (2, "marvelous", 3),
]
texts = [
    f'<tag id="{ids}">{text}<\\tag>'  # TODO: handle HTML quoting?
    for (number, text, ids) in list1
]
text = "\r\n".join(texts)

相关问题 更多 >