字符串拼接小功能

    之前寫了一段很有意思的代碼,一個小的功能,代碼比較精簡,在此記錄一下。

"數據是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))

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章