Python 迭代行,只更改一个字符

Python 迭代行,只更改一个字符,python,list,loops,permutation,Python,List,Loops,Permutation,我有一个像这样的文件 N1 1.023 2.11 3.789 Cl1 3.124 2.4534 1.678 Cl2 # # # Cl3 # # # Cl4 Cl5 N2 Cl6 Cl7 Cl8 Cl9 Cl10 N3 Cl11 Cl12 Cl13 Cl14 Cl15 这三个数字一直在下降 我想做的几乎是一个排列。这是3个数据集,集合1是N1-Cl5,集合2是N2-Cl10,集合3是N3-end 我想要N和Cl的每一个组合。例如,第一个输出是 Cl1 N1

我有一个像这样的文件

N1 1.023 2.11 3.789 

Cl1 3.124 2.4534 1.678

Cl2 # # #

Cl3 # # #

Cl4

Cl5

N2

Cl6

Cl7

Cl8

Cl9

Cl10

N3

Cl11


Cl12

Cl13

Cl14

Cl15
这三个数字一直在下降

我想做的几乎是一个排列。这是3个数据集,集合1是N1-Cl5,集合2是N2-Cl10,集合3是N3-end

我想要N和Cl的每一个组合。例如,第一个输出是

Cl1

N1

Cl2
然后其他一切都一样。下一组是Cl1、Cl2、N1、Cl3……等等

我有一些代码,但它不会做我想要的,因为它会知道有三个单独的数据集。我应该将这三个数据集放在三个不同的文件中,然后使用如下代码进行组合:

list1 = ['Cl1','Cl2','Cl3','Cl4', 'Cl5']

for line in file1:
    line.replace('N1', list1(0))
    list1.pop(0)
    print >> file.txt, line,

还是有更好的方法??提前感谢

这应该可以做到:

from itertools import permutations

def print_permutations(in_file):
    separators = ['N1', 'N2', 'N3']
    cur_separator = None
    related_elements = []

    with open(in_file, 'rb') as f:
        for line in f:
            line = line.strip()

            # Split Nx and CIx from numbers.
            value = line.split()[0]

            # Found new Nx. Print previous permutations.
            if value in separators and related_elements:
                for perm in permutations([cur_separator] + related_elements)
                    print perm
                cur_separator = line
                related_elements = []
            else:
                # Found new CIx. Append to the list.
                related_elements.append(value)

您可以使用regex查找“N”模式的行号,然后使用这些行号对文件进行切片:

import re
n_pat = re.compile(r'N\d')
N_matches = []
with open(sample, 'r') as f:
    for num, line in enumerate(f):
        if re.match(n_pat, line):
            N_matches.append((num, re.match(n_pat, line).group()))

>>> N_matches
[(0, 'N1'), (12, 'N2'), (24, 'N3')]
在计算出这些模式出现的行号后,您可以使用
itertools.islice
将文件分解为列表:

import itertools

first = N_matches[0][0]
final = N_matches[-1][0]
step = N_matches[1][0]
data_set = []
locallist = []

while first < final + step:
    with open(file, 'r') as f:
        for item in itertools.islice(f, first, first+step):
            if item.strip():
                locallist.append(item.strip())
        dataset.append(locallist)
        locallist = []
    first += step
在那之后,我对您想要做的事情有点模糊,但我认为您想要数据集的每个子列表的排列?如果是这样,您可以使用
itertools.permutations
在数据集的各个子列表上查找排列:

for item in itertools.permutations(dataset[0]):
    print(item)
etc.
最后一个注释:

假设我正确理解你在做什么,排列的数量将是巨大的。你可以通过计算项目数的阶乘来计算有多少个排列。任何超过10(10!)的东西都将产生超过300亿个排列

for item in itertools.permutations(dataset[0]):
    print(item)
etc.