在创建列表的子列表时遇到麻烦

问题描述 投票:0回答:1

我的任务是创建组合,更像是库文件的某些属性行的笛卡尔积。我目前面临将相同属性(当然相邻参数不同)分组为列表子列表的问题。

以下是我的算法:

  1. 从库文件中获取输入属性,并将它们输入到基于正则表达式“attr[数值]”的列表中。

  2. 然后将相同的 attr[数值] 分组为列表的子列表。

  3. 对所有子列表执行笛卡尔积。

我目前陷入了第 2 步,因此我请求对我的代码进行必要的修改,或者提供更好的解决方案。

########################

输入示例:

attr1 苹果 1
attr1 香蕉 2

attr2 葡萄 1
attr2 橙子 2

attr3 西瓜 0

########################

输出示例:

attr1 苹果 1
attr2 葡萄 1
attr3 西瓜 0

attr1 苹果 1
attr2 橙子 2
attr3 西瓜 0

attr1 香蕉 2
attr2 葡萄 1
attr3 西瓜 0 。 。 .

下面是代码。我期待的输出如下。 我想要的输出:

[['attr1 苹果 1','attr1 香蕉 2'],['attr2 葡萄 1','attr2 橙子 2'],['attr3 西瓜 0']]

import re

# regex pattern definition
pattern = re.compile(r'attr\d+')

# Open the file for reading
with open(r"file path") as file:
    # Initialize an empty list to store matching lines
    matching_lines = []

    # reading each line 
    for line in file:
        # regex pattern match
        if pattern.search(line):
            # matching line append to the list
            matching_lines.append(line.strip())

# Grouping the  elements based on the regex pattern

grouped_elements = []
current_group = []

for sentence in matching_lines:
    if pattern.search(sentence):
        current_group.append(sentence)
    else:
        if current_group:
            grouped_elements.append(current_group)
        current_group = [sentence]

# Print the grouped elements
for group in grouped_elements:
    print(group)

python list combinations cartesian-product sublist
1个回答
0
投票
grouped_elements = [
    ['A', 'B', 'C'],
    ['D', 'E'],
    ['F', 'G', 'H', 'I']
]

count = [len(row) for row in grouped_elements]
count.append(1)
# count is [3, 2, 4, 1]

for i in range(len(count) - 2, -1, -1):
    count[i] = count[i] * count[i + 1]

# count is [3 * 2 * 4 * 1, 2 * 4 * 1, 4 * 1, 1]

for i in range(count[0]):
    row = []
    for j in range(len(grouped_elements)):
        idx = (i // count[j + 1]) % len(grouped_elements[j])
        
        row.append(grouped_elements[j][idx])
    
    print(row)
result

['A', 'D', 'F']
['A', 'D', 'G']
['A', 'D', 'H']
['A', 'D', 'I']
['A', 'E', 'F']
['A', 'E', 'G']
['A', 'E', 'H']
['A', 'E', 'I']
['B', 'D', 'F']
['B', 'D', 'G']
['B', 'D', 'H']
['B', 'D', 'I']
['B', 'E', 'F']
['B', 'E', 'G']
['B', 'E', 'H']
['B', 'E', 'I']
['C', 'D', 'F']
['C', 'D', 'G']
['C', 'D', 'H']
['C', 'D', 'I']
['C', 'E', 'F']
['C', 'E', 'G']
['C', 'E', 'H']
['C', 'E', 'I']
© www.soinside.com 2019 - 2024. All rights reserved.