Reputation: 213
Hi I have a 2d list that has 3 elements I have concatenated some of the elements using the following code
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)
and this produces the following output
<tag id = 3>hello<\tag>
<tag id = 4>excelent<\tag>
<tag id =3>marvelous<\tag>
and this is correct, my question is there a way to do this using list comprehension, or is there a more pythonic way of achieving this same outcome.
Upvotes: 0
Views: 85
Reputation: 13069
You could reduce the whole thing to a one-liner, but I suggest that a reasonable compromise is probably still to use a for
loop over your list, but in the for
loop target you can unpack the sublists directly into the relevant variables. In any case there is no need for looping over index rather than the actual contents of list1
. Using an f-string (in recent Python versions) will also help tidy things up.
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)
You could also consider using the conventional dummy variable _
in place of number
here, because you are not actually using the value:
for _, listText, ids in list1:
Upvotes: 1
Reputation: 16772
Using list-comprehension:
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>']
Edit:
If you want to have the double quotes in the tags text:
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>']
Upvotes: 1
Reputation:
iterate lambda function and use 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)))
Upvotes: 0
Reputation: 168913
Using f-strings and unpacking the tuple elements in the list comprehension makes this neatly readable:
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)
Upvotes: 0