简体   繁体   English

在递归函数python中返回字符串列表

[英]return a list of strings in a recursive function python

I'm trying to return a list of strings from the function Groups(s,k) where basically, the list of strings of 'k' elements from string 's' k>=0 and k<= len(s) and these elements in the these strings occur in the same order as 's' as shown below 我正在尝试从功能Groups(s,k)返回一个字符串列表,其中基本上是字符串's'k> = 0和k <= len(s)的'k'元素的字符串列表,而这些这些字符串中的元素以与“ s”相同的顺序出现,如下所示

Groups("abcde", 2) → ["ab","ac","ad","ae","bc","bd","be","cd","ce,"de"] 群组(“ abcde”,2)→[“” ab“,” ac“,” ad“,” ae“,” bc“,” bd“,” be“,” cd“,” ce,“ de”]

Groups("abcde",5) → ["abcde"] 群组(“ abcde”,5)→[“” abcde“]
Groups("abcde",1) → ["a","b","c","d","e"] 组(“ abcde”,1)→[“ a”,“ b”,“ c”,“ d”,“ e”]

I'm really sorry for my wording of the question as it's hard to understand but here is what I have so far: 对于这个问题的措辞,我感到非常抱歉,因为这很难理解,但到目前为止,我的意思是:

    def Groups(s,k):
        if k == 0 or k > len(s):
            return [""]

        return [ i*k for i in s if k ==1]
        if k > 1 and k <= 5:
            return[ x for y in s y for x in s]

I would greatly appreciate any help:) 我将不胜感激任何帮助:)

I think combinations is the word you are looking for: 我认为combinations是您要寻找的词:

list(''.join(letters) for letters in combinations("abcde", 2))
# returns ['ab', 'ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cd', 'ce', 'de']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM