0

I have two wordlists, as per examples below:

wordlist 1 :

code1
code2
code3

wordlist 2 :

11
22
23

I want to take wordlist 2 and put every number in a line with first line in wordlist 1

example of the output :

code111
code122
code123
code211
code222
code223
code311
.
.

Can you please help me with how to do it? Thanks!

3 Answers3

1

You can run two nested for loops to iterate over both lists, and append the concatenated string to a new list.
Here is a little example:

## create lists using square brackets
wordlist1=['code1', ## wrap something in quotes to make it a string
           'code2','code3']
wordlist2=['11','22','23']

## create a new empty list
concatenated_words=[]

## first for loop: one iteration per item in wordlist1
for i in range(len(wordlist1)):
    ## word with index i of wordlist1 (square brackets for indexing)
    word1=wordlist1[i]
    ## second for loop: one iteration per item in wordlist2
    for j in range(len(wordlist2)):
        word2=wordlist2[j]
        ## append concatenated words to the initially empty list
        concatenated_words.append(word1+word2)

## iterate over the list of concatenated words, and print each item
for k in range(len(concatenated_words)):
    print(concatenated_words[k])
Kantenkopp
  • 65
  • 7
  • i have tried to change the list to file but it turn out with an error – Mustapha Mouzaki Jun 14 '16 at 22:46
  • If you have python installed, open a text editor, paste the code example, and save it to a file called `string_concatenation.py` (a python file). Then, open a terminal, navigate to the folder of the file, and type `python string_concatenation.py`. This should print the desired output in your terminal. – Kantenkopp Jun 14 '16 at 23:22
  • no i mean wordlist2 i want to take it from a file.txt – Mustapha Mouzaki Jun 15 '16 at 00:02
0

list1 = ["text1","text2","text3","text4"] list2 = [11,22,33,44] def iterativeConcatenation(list1, list2): result = [] for i in range(len(list2)): for j in range(len(list1)): result = result + [str(list1[i])+str(list2[j])] return result

adamus
  • 1
0

have you figured it out? depends on if you want to input the names on each list, or do you want it to for instance automatically read then append or extend a new text file? I am working on a little script atm and a very quick and simple way, lets say u want all text files in the same folder that you have your .py file:

import os

#this makes a list with all .txt files in the folder.
list_names = [f for f in os.listdir(os.getcwd()) if f.endswith('.txt')]
for file_name in list_names:
    with open(os.getcwd() + "/" + file_name) as fh:
        words = fh.read().splitlines()

with open(outfile, 'a') as fh2:
    for word in words:
        fh2.write(word + '\n')
MartenCatcher
  • 2,713
  • 8
  • 26
  • 39