2017-04-12 15 views
1
def number_of_cases(list_data): 
    from itertools import combinations_with_replacement 
    mylist = list_data 
    result = list(combinations_with_replacement(mylist, 2)) 
    return(result) 

def main(): 
    result = number_of_cases(['a', 'b']) 
    print(result) 

結果:以下のように私は組み合わせの間にスペースを望んでいない以下のようにコードを作成する方法は?

>>> main() 
[('a', 'a'), ('a', 'b'), ('b', 'b')] 

... ..結果以下のようにするコードを作成する方法 ?

>>> a = ['a', 'b', 'c'] 
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']' 

>>> a = ['a', 'a'] 
['aa'] 

>>> a = [1, 2, 3, 'a'] 
['11', '12', '13', '1a', '21', '22', '23', '2a', '31', '32', '33', '3a', 'a1', 'a2', 'a3', 'aa'] 

答えて

0

あなたはliteral string interpolation(Pythonの3.6で新しい)を使用することがあります。

>>> [f'{x}{y}' for x,y in combinations_with_replacement([1,2,3,'a'], 2)] 
['11', '12', '13', '1a', '22', '23', '2a', '33', '3a', 'aa'] 
+0

は、 'X + y'同じように簡単ではないですか? – Barmar

+0

なし、実施例の一つは整数と文字列の組み合わせを持っていたので – wim

+0

方法combinations_with_replacement([1,2,3におけるxの '[ "{0} {1}" 形式(x、y)は、Yについて、」 a ']、2)] 'Python 2でも動作させるには? – JohanL

0

あなたが(STRする必要がある)の要素の文字列としてそれらすべてを取得した後、単に結果リストの各要素に参加します。

def number_of_cases(list_data): 
    from itertools import combinations_with_replacement 
    list_data = [str(data) for data in list_data] 
    mylist=list_data 
    result=list(combinations_with_replacement(mylist,2)) 
    joined_result = [] 
    for choice in result: 
      joined = ''.join(choice) 
      joined_result.append(joined) 
    return(joined_result) 

def main(): 
    result=number_of_cases(['a','b']) 
    print(result) 

[ 'AA'、 'AB'、 'BB']

+0

一つ以上の要素を行くが、実施例の一つのように、整数ではなく文字である場合、これは動作しません。 – JohanL

+0

修正されました。 5文字 –

関連する問題