【问题标题】:Combining Elements Within a List to Form a New List [duplicate]组合列表中的元素以形成新列表 [重复]
【发布时间】:2021-05-24 02:23:13
【问题描述】:

我不确定我想要做什么的技术术语,但这就是它的要点。我有以下清单:

x = ['a', 'b', 'c']

我想创建一个新列表 y 其中len(y) = 2 ** len(x) 这样:

y = ['∅', 'a', 'b', 'c', 'a,b', 'a,c', 'b,c', 'a,b,c']

我不确定在循环 x 以创建所需的列表 y 时使用什么操作。

【问题讨论】:

  • 你想遍历子集,所以使用itertools
  • 你想要的列表中的第一个元素'∅' 是什么意思?
  • @Anonymous 是空集的常用数学符号

标签: python list


【解决方案1】:

虽然这比 itertools 效率低得多,但如果您不允许使用库,您可以创建一个递归函数来生成幂集并在列表理解中使用 join() 组装字符串:

def powerSet(L):
    return [[]] if not L else [c for p in powerSet(L[1:]) for c in (p,L[:1]+p)]

x = ['a','b','c']
y = [",".join(s) or "ø" for s in powerSet(x)]

print(y)
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']

您也可以直接在迭代函数中执行此操作,该函数将所有先前的组合与列表中的每个字母一起扩展:

def allCombos(L):
    result = [""]
    for c in L:
        result.extend([f"{r},{c}" if r else c for r in result])
    result[0] = "ø"
    return result

print(allCombos(x))
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2014-12-31
    • 2017-09-16
    • 2013-01-21
    • 2023-02-19
    相关资源
    最近更新 更多