我想要一个程序,把每种组合都写到文本文件的不同一行中

4 投票
4 回答
5967 浏览
提问于 2025-04-11 09:33

我想写一个程序,把一组变量的所有组合打印到一个文本文件里,生成一个单词列表。每个结果应该单独写在一行上,并且把1位、2位和3位的所有结果都写到同一个文本文件里。

有没有简单的方法可以用Python写一个程序来实现这个呢?下面是我期待的输出示例,展示了1位、2位和3位的所有二进制数字组合:

Output:
0  
1

00  
01  
10  
11

000  
001  
010  
011  
100  
101  
110  
111

4 个回答

2

下面是一个基本的函数,用来生成一个列表的所有排列组合。在这个方法中,排列组合是通过使用生成器来“懒惰”地创建的。

def perms(seq):
    if seq == []:
        yield []
    else:
        res = []
        for index,item in enumerate(seq):
            rest = seq[:index] + seq[index+1:]
            for restperm in perms(rest):
                yield [item] + restperm

alist = [1,1,0]
for permuation in perms(alist):
    print permuation
3

在编程中,有时候我们需要把一些数据从一个地方传到另一个地方。比如说,你在一个程序里计算了一个结果,然后想把这个结果用在另一个程序里。这就像是把一份文件从一个文件夹搬到另一个文件夹。

为了做到这一点,我们通常会使用一些特定的方式来传递这些数据。比如说,有的编程语言允许你直接把数据传递给另一个函数,就像是把一张纸递给朋友一样。

另外,有些时候我们需要把数据存储起来,以便以后使用。这就像是把文件放进一个盒子里,等需要的时候再拿出来。

总之,数据的传递和存储是编程中非常重要的部分,理解这些概念能帮助你更好地写出有效的代码。

# Given two lists of strings, return a list of all ways to concatenate
# one from each.
def combos(xs, ys):
    return [x + y for x in xs for y in ys]

digits = ['0', '1']
for c in combos(digits, combos(digits, digits)):
    print c

#. 000
#. 001
#. 010
#. 011
#. 100
#. 101
#. 110
#. 111
3

一个简单的解决方案,可以解决这个问题,并且适用于你可能遇到的任何应用,就是这个:

def combinations(words, length):
    if length == 0:
        return []
    result = [[word] for word in words]
    while length > 1:
        new_result = []
        for combo in result:
            new_result.extend(combo + [word] for word in words)
        result = new_result[:]
        length -= 1
    return result

基本上,这个方法会在内存中逐步构建出所有组合的树形结构,然后返回这些组合。不过,这种方法会占用很多内存,所以对于大规模的组合来说并不实用。

另一个解决问题的方法其实是使用计数,然后把生成的数字转化为单词列表中的单词。为此,我们首先需要一个函数(叫做 number_to_list()):

def number_to_list(number, words):
    list_out = []
    while number:
        list_out = [number % len(words)] + list_out
        number = number // len(words)
    return [words[n] for n in list_out]

这个函数实际上是一个把十进制数字转换成其他进制的系统。接下来,我们写一个计数函数;这个相对简单,将构成应用的核心:

def combinations(words, length):
    numbers = xrange(len(words)**length)
    for number in numbers:
        combo = number_to_list(number, words)
        if len(combo) < length:
            combo = [words[0]] * (length - len(combo)) + combo
        yield combo

这是一个Python生成器;使用生成器可以减少内存的使用。将数字转化为单词列表后,还需要做一些工作,因为这些列表需要填充,以达到所需的长度。用法如下:

>>> list(combinations('01', 3))
[['0', '0', '0'], ['0', '0', '1'],
['0', '1', '0'], ['0', '1', '1'],
['1', '0', '0'], ['1', '0', '1'],
['1', '1', '0'], ['1', '1', '1']]

如你所见,你会得到一个列表的列表。每个子列表都包含了一系列原始单词;你可以像这样使用 map(''.join, list(combinations('01', 3))) 来获取以下结果:

['000', '001', '010', '011', '100', '101', '110', '111']

然后你可以把这些写入磁盘;不过,更好的主意是利用生成器的内置优化,做一些这样的事情:

fileout = open('filename.txt', 'w')
fileout.writelines(
    ''.join(combo) for combo in combinations('01', 3))
fileout.close()

这样只会使用必要的内存(足够存储一个组合)。希望这对你有帮助。

撰写回答