简体   繁体   中英

Concatenate Multiple Strings From Multiple Lists

I have the following:


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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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