Concatenate Multiple Strings From Multiple Lists

Viewed 234

I have the following:

import pandas as pd

Roads =['Motorways','Streets','Avenues']

Countries =  ['England','Scotland','Wales']

Visuals = ['Graph','Table']


TabNames = [pd.Series(Roads)+ pd.Series(Countries) + pd.Series(Visuals).tolist()]

print(TabNames) 

How would I print the output so that it would be like 'Motorways England Graph', Motorways Scotland Graph', 'Motorways Wales Graph', 'Streets England Graph' so on and so forth.

How do I then copy the output or have it spit it out to a .txt file?

2 Answers

You could try this without the need to import any library:

Roads = ['Motorways', 'Streets', 'Avenues']
Countries = ['England', 'Scotland', 'Wales']
Visuals = ['Graph', 'Table']

with open('result.txt', 'w') as write_file:
    for road in Roads:
        for country in Countries:
            for visual in Visuals:
                sentence = road + ' ' + country + ' ' + visual
                print(sentence)
                write_file.write(sentence)
                write_file.write('\n')
    
write_file.close()

Output:

Motorways England Graph
Motorways England Table
Motorways Scotland Graph
Motorways Scotland Table
Motorways Wales Graph
Motorways Wales Table
Streets England Graph
Streets England Table
Streets Scotland Graph
Streets Scotland Table
Streets Wales Graph
Streets Wales Table
Avenues England Graph
Avenues England Table
Avenues Scotland Graph
Avenues Scotland Table
Avenues Wales Graph
Avenues Wales Table

Try this:

index = pd.MultiIndex.from_product([Roads, Countries, Visuals], names = ["Roads", "Countries", "Visuals"])
pd.DataFrame(index = index).reset_index()
Related