繁体   English   中英

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

[英]concatenate 2d list with list comprehension instead of a for loop

嗨,我有一个包含 3 个元素的 2d 列表,我使用以下代码连接了一些元素

    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)

这会产生以下 output

<tag id = 3>hello<\tag> 
<tag id = 4>excelent<\tag> 
<tag id =3>marvelous<\tag>

这是正确的,我的问题是有没有办法使用列表理解来做到这一点,或者是否有更多的 pythonic 方法来实现同样的结果。

使用列表理解:

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

OUTPUT:

['<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])

OUTPUT:

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

您可以将整个事情减少到一行,但我建议合理的折衷方案可能仍然是在您的列表上使用for循环,但在for循环目标中,您可以将子列表直接解压缩到相关变量中。 在任何情况下都不需要遍历 index 而不是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)

您还可以考虑在这里使用传统的虚拟变量_代替number ,因为您实际上并没有使用该值:

for _, listText, ids in list1:

使用 f-strings 并在列表推导式中解包元组元素使其清晰可读:

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)

迭代 lambda function 并使用map()

list1 = [(1, "hello", 3), (1, "excelent", 4), (2, "marvelous", 3)]
text = map(lambda x: f'<tag id = {x[2]}>{x[1]}<\\tag>', list1)
print('\r\n'.join(list(text)))

暂无
暂无

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

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