Concatenate two strings of different lists based on a value

Viewed 41

I have the following variable z:

z =   [
        ['8575748' , 't', 'TextA.\n'],
        ['8575748' , 'a', 'TextB.\n'],
        ['10556298', 't', 'TextC.\n'],
        ['10556298', 'a', 'TextD.\n'],

       ]

'TextA\n', 'TextB\n', 'TextC\n', and 'TextD\n' are nothing but text samples parsed from .txt file. 't' and 'a'stand for title and abstract, respectively.

I am trying the produce the following output:

[('8575748', 'TextA.' + ' ' + 'TextB.'), ('10556298', 'TextC.' + ' ' + 'TextD.')]

That is title and abstract to be concatenated with space ' '. Note that there is \n at the end of each text which is subject to be removed during concatenating.

I tried the following:

(list(zip(z[0], z[1]))[0][0] , \
 list(zip(z[0], z[1]))[2][0].strip('\n') + list(zip(z[0], z[1]))[2][1].strip('\n'))

Which looks long code. I want to have a fast and clean code.

1 Answers
z = [
    ["8575748", "t", "TextA.\n"],
    ["8575748", "a", "TextB.\n"],
    ["10556298", "t", "TextC.\n"],
    ["10556298", "a", "TextD.\n"],
]

out = {}
for id_, _, txt in z:
    out.setdefault(id_, []).append(txt.strip())

out = [(k, " ".join(v)) for k, v in out.items()]
print(out)

Prints:

[('8575748', 'TextA. TextB.'), ('10556298', 'TextC. TextD.')]
Related