Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何结合';比如';嵌套列表中的元素?_Python_Python 3.x_Recursion_Sequence - Fatal编程技术网

Python 如何结合';比如';嵌套列表中的元素?

Python 如何结合';比如';嵌套列表中的元素?,python,python-3.x,recursion,sequence,Python,Python 3.x,Recursion,Sequence,我有3个嵌套列表: STEP = [['S', '1', 'B', '3'], ['S', '3', 'B', '11'], ['S', '5', 'B', '12'], ['S', '4', 'B', '13'], ['S', '2', 'B', '14']] TRANSITION = [['T', '2', 'B', '4'], ['T', '7', 'B', '4'], ['T', '3', 'S', '4'], ['T', '5', 'S', '5'], ['T', '1', 'S',

我有
3个
嵌套列表:

STEP = [['S', '1', 'B', '3'], ['S', '3', 'B', '11'], ['S', '5', 'B', '12'], ['S', '4', 'B', '13'], ['S', '2', 'B', '14']]

TRANSITION = [['T', '2', 'B', '4'], ['T', '7', 'B', '4'], ['T', '3', 'S', '4'], ['T', '5', 'S', '5'], ['T', '1', 'S', '2'], ['T', '8', 'S', '2'], ['T', '6', 'S', '1'], ['T', '9', 'S', '2'], ['T', '4', 'S', '1'], ['T', '10', 'S', '1']]

BRANCH = [['B', '3', 'T', '1'], ['B', '3', 'T', '7'], ['B', '4', 'S', '3'], ['B', '11', 'T', '3'], ['B', '11', 'T', '5'], ['B', '12', 'T', '6'], ['B', '12', 'T', '8'], ['B', '13', 'T', '4'], ['B', '13', 'T', '9'], ['B', '14', 'T', '2'], ['B', '14', 'T', '10']]
每个元素都保存以下信息:

# Example

STEP[0]  =  ['S', '1', 'B', '3']
其中:

  • “S”是
    步骤
    类型
  • “1”是
    步骤
    编号id
  • “B”是链接的
    分支
    类型
  • “3”是链接的
    分支
    编号id
步骤开始
数据都是链接的,因此使用链接引用可以找到下一个元素和下一个元素,直到到达另一个
步骤

这是数据的一些参数:

  • 步骤
    连接到单个
    分支
  • 分支
    连接到一个或多个
    转换
  • 转换
    可以连接到单个
    分支
    步骤
分支
数据可以有一个分叉,其中单个
分支
id有一个或多个用于
转换的选项

我想将这些叉子组合成相同的“分支”id,即:

# BRANCH[0] and BRANCH[1] both have an id of '3' 
# therefore, need to be combined

BRANCH[0] = ['B', '3', 'T', ['1', '7']] 
这样做是为了创建一个新列表,该列表将所有“like”分支组合在一起

到目前为止,我的尝试(没有取得很大进展):
我很确定有更简单的方法,但根据您的示例,您可以尝试:

BRANCH = [['B', '3', 'T', '1'], ['B', '3', 'T', '7'], ['B', '4', 'S', '3'], ['B', '11', 'T', '3'], ['B', '11', 'T', '5'], ['B', '12', 'T', '6'], ['B', '12', 'T', '8'], ['B', '13', 'T', '4'], ['B', '13', 'T', '9'], ['B', '14', 'T', '2'], ['B', '14', 'T', '10']]
tmp = {}
final = []
for x in BRANCH:
    if not f"{x[0]}-{x[1]}" in tmp:
        tmp[f"{x[0]}-{x[1]}"] = [x[3]]
    else:
        tmp[f"{x[0]}-{x[1]}"].append(x[3])

for k, v in tmp.items():
    one, two = k.split("-")
    for x in BRANCH:
        if x[0] == one and x[1] == two:
            if not [one, two, x[2], v] in final:
                final.append([one, two, x[2], v])

print(final)


您可以使用分支相似性测试,然后在分支上循环检查相似性。其余的只是防止重复,并将数据转换成列表。我将数据随机化,并添加了另一个项目,以检查它不会阻塞超过一对类似的分支

# Check similarity (first three fields equal).
def similar_p(one, two):
    for item in range(len(one) - 1):
        if one[item] != two[item]:
            return False
    return True

# Data.  Works sorted and not.
branches = [
    ['B', '14', 'T', '2'],
    ['B', '12', 'T', '6'],
    ['B', '14', 'T', '10'],
    ['B', '13', 'T', '4'],
    ['B', '3', 'T', '9'],
    ['B', '12', 'T', '8'],
    ['B', '13', 'T', '9'],
    ['B', '3', 'T', '7'],
    ['B', '4', 'S', '3'],
    ['B', '11', 'T', '5'],
    ['B', '3', 'T', '1'],
    ['B', '11', 'T', '3'],
    ]

merge_dict = {}

# Loop over branches.  Uncomment print statements to watch the action.
for i in range(len(branches)):
    # print('check for similars to branch {}'.format(branches[i]))
    # try/except to ensure the dictionary item is actually there.
    try:
        # print(merge_dict[tuple(branches[i][0:3])])
        if branches[i][3] not in merge_dict[tuple(branches[i][0:3])]:
            merge_dict[tuple(branches[i][0:3])].append(branches[i][3])
            # print('initial appending to branch {}'.format(branches[i]))
    except (KeyError):
        merge_dict[tuple(branches[i][0:3])] = [branches[i][3]]
        # print('starting branch {}'.format(branches[i]))
    for j in range((i + 1), len(branches), 1):
        if similar_p(branches[i], branches[j]):
            if branches[j][3] not in merge_dict[tuple(branches[i][0:3])]:
                merge_dict[tuple(branches[i][0:3])].append(branches[j][3])
                # print('appending similar branch {} to branch {}'.format(branches[j], branches[i]))

merged = list()

# Massage into a list.  Sorting is on you, kid.
for k,v in merge_dict.items():
    if len(v) == 1:
        merged.append([*k, *v])
    else:
        merged.append([*k, v])

print(merged)
输出:

[['B', '14', 'T', ['2', '10']], ['B', '12', 'T', ['6', '8']], ['B', '13', 'T', ['4', '9']], ['B', '3', 'T', ['9', '7', '1']], ['B', '4', 'S', '3'], ['B', '11', 'T', ['5', '3']]]

到目前为止,您尝试了什么?我尝试了一些循环,尝试检查当前选定的分支是否与链接的转换编号方面的任何其他分支匹配。如果他们真的这样做了,就把它们附加到一个分支id上。这一直是个障碍。你能在这里添加你的代码吗,这将是其他人帮助你的一个很好的起点是的,当然,我会用我到目前为止的知识更新这个问题
# Check similarity (first three fields equal).
def similar_p(one, two):
    for item in range(len(one) - 1):
        if one[item] != two[item]:
            return False
    return True

# Data.  Works sorted and not.
branches = [
    ['B', '14', 'T', '2'],
    ['B', '12', 'T', '6'],
    ['B', '14', 'T', '10'],
    ['B', '13', 'T', '4'],
    ['B', '3', 'T', '9'],
    ['B', '12', 'T', '8'],
    ['B', '13', 'T', '9'],
    ['B', '3', 'T', '7'],
    ['B', '4', 'S', '3'],
    ['B', '11', 'T', '5'],
    ['B', '3', 'T', '1'],
    ['B', '11', 'T', '3'],
    ]

merge_dict = {}

# Loop over branches.  Uncomment print statements to watch the action.
for i in range(len(branches)):
    # print('check for similars to branch {}'.format(branches[i]))
    # try/except to ensure the dictionary item is actually there.
    try:
        # print(merge_dict[tuple(branches[i][0:3])])
        if branches[i][3] not in merge_dict[tuple(branches[i][0:3])]:
            merge_dict[tuple(branches[i][0:3])].append(branches[i][3])
            # print('initial appending to branch {}'.format(branches[i]))
    except (KeyError):
        merge_dict[tuple(branches[i][0:3])] = [branches[i][3]]
        # print('starting branch {}'.format(branches[i]))
    for j in range((i + 1), len(branches), 1):
        if similar_p(branches[i], branches[j]):
            if branches[j][3] not in merge_dict[tuple(branches[i][0:3])]:
                merge_dict[tuple(branches[i][0:3])].append(branches[j][3])
                # print('appending similar branch {} to branch {}'.format(branches[j], branches[i]))

merged = list()

# Massage into a list.  Sorting is on you, kid.
for k,v in merge_dict.items():
    if len(v) == 1:
        merged.append([*k, *v])
    else:
        merged.append([*k, v])

print(merged)
[['B', '14', 'T', ['2', '10']], ['B', '12', 'T', ['6', '8']], ['B', '13', 'T', ['4', '9']], ['B', '3', 'T', ['9', '7', '1']], ['B', '4', 'S', '3'], ['B', '11', 'T', ['5', '3']]]