之前写了一段很有意思的代码,一个小的功能,代码比较精简,在此记录一下。
"数据是list"
src_list = [["a", "c"], ["c", "d"], ["a", "2"], ["2", "d"], ["a", "1"], ["1", "d"],
["d", "e"], ["e", "h"], ["c", "f"], ["f", "g"], ["m", "2"], ["m", "f"]]
观察数据可以发现 a,c c,d ... 需要实现的目标是如图:
思路递归操作简单、优美,代码实现:
#! -*- coding: utf-8 -*-
# @File : test.py
# @Author: bingjia
# @Date : 2019/9/18
# @Desc : 功能性函数
src_list = [["a", "c"], ["c", "d"], ["a", "2"], ["2", "d"], ["a", "1"], ["1", "d"],
["d", "e"], ["e", "h"], ["c", "f"], ["f", "g"], ["m", "2"], ["m", "f"]]
def create_str(test_list):
"""
将list中首尾相连的字符拼接成字符串
:param test_list: 待处理list
:return: 字符串
"""
result_list = []
# 列数据
column_1, column_2 = [x[0] for x in test_list], [x[1] for x in test_list]
# 找list头部
head_list = list(set([x for x in column_1 if x not in column_2]))
def recursive(data_list, string):
"""
递归主体函数
:param data_list: 待处理的元素
:param string: 拼接生成的字符串
:return:
"""
for data in data_list:
if column_1.count(data) == 0:
result_list.append(string + data)
else:
temp_list = [x[1] for x in test_list if x[0] is data]
recursive(temp_list, string + data)
for i in range(len(head_list)):
recursive([x[1] for x in test_list if x[0] is head_list[i]], head_list[i])
return result_list
print(create_str(src_list))