将两个单词列表合并为一个文件

时间:2016-06-14 17:50:32

标签: linux merge brute-force

我有两个单词列表,如下例所示:

wordlist 1:

code1
code2
code3

wordlist 2:

11
22
23

我想采用 wordlist 2 并将每个数字放在第一行的第一行 wordlist 1

输出示例:

code111
code122
code123
code211
code222
code223
code311
.
.

你能帮我解决一下这个怎么办吗?谢谢!

3 个答案:

答案 0 :(得分:1)

您可以运行两个嵌套for循环来遍历两个列表,并将连接的字符串附加到新列表。
这是一个小例子:

## 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])

答案 1 :(得分:0)

list1 = [" text1"," text2"," text3"," text4"] list2 = [11,22,33,44] def iterativeConcatenation(list1,list2):     result = []     for in in range(len(list2)):         对于范围内的j(len(list1)):             result = result + [str(list1 [i])+ str(list2 [j])]     返回结果

答案 2 :(得分:0)

你知道了吗?取决于是要在每个列表上输入名称,还是要例如自动读取然后追加或扩展新文本文件的名称?我正在研究一个小的脚本atm,并且以一种非常快速和简单的方式,让我们说您希望所有文本文件都与您的.py文件位于同一文件夹中:

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