【问题标题】:possible combinations of strings in an array in python?python中数组中字符串的可能组合?
【发布时间】:2016-07-22 17:31:27
【问题描述】:

arr=['one','two','three']

结果必须是这样的: onetwo,twothree,onethree

itertools.permutations 在这种情况下不起作用。

我们可以通过简单地添加 for 循环并附加它们来做到这一点,这适用于小数组,但对于大数组需要时间。
我想知道(like itertools.permutations)this 有什么方法可以实现吗?

【问题讨论】:

    标签: python arrays python-3.x python-3.4 itertools


    【解决方案1】:

    也许你想要的是itertools.combinations

    >>> [''.join(comb) for comb in (itertools.combinations(arr, 2))]
    ['onetwo', 'onethree', 'twothree']
    

    【讨论】:

    • 有什么方法可以将其应用于两个不同的数组。我的意思是 arr1=['name1','name2'];arr2=['name3','name4'].output 应该是 @ 987654323@
    【解决方案2】:

    两个列表

    • 创建一个与其他列表长度相等的列表
    • 用其他列表压缩新列表
    • 将所有子列表放在一起
    • 加入列表
    from itertools import permutations
    
    arr1=['name1','name2']
    arr2=['name3','name4']
    
    set( map(lambda x: ''.join(x),reduce( lambda x,y:x+y, [  zip(i,arr1) for i in permutations(arr2,len(arr1)) ] ) ) )
    
    output:
    
    set(['name3name1', 'name3name2', 'name4name1', 'name4name2'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多