【问题标题】:Python generate all 3 letter combinationsPython生成所有3个字母组合
【发布时间】:2021-03-10 19:31:29
【问题描述】:

我想得到一个列表中所有 3 个字母组合的列表,例如:

aaa, aab, aac

它也必须包含数字。 到目前为止我的代码是

letters = list(string.ascii_lowercase)
letters.extend([i+b+a for i in letters for b in letters for a in letters])

但此代码返回的组合少于 3 位,并且没有数字。

【问题讨论】:

  • 你已经尝试了什么?
  • @C_Z_ letters = list(string.ascii_lowercase) letters.extend([i+b+a for i in letters for b in letters for a in letters]) 这存储在一个列表中,其中现在还可以,但我希望尽量减少内存的使用。
  • 好的,请使用该代码更新您的问题。
  • but with numbers in it too 我们怎么知道哪些数字
  • @coderoftheday,我认为他的意思不是数字,而是数字。

标签: python


【解决方案1】:

在标准库包itertools中使用combinations

import string
from itertools import combinations

letters = list(string.ascii_lowercase)
letters.extend(string.digits)

for comb in combinations(letters, 3):
    print(''.join(comb))

【讨论】:

    【解决方案2】:

    如果你不想使用任何包,这个答案来自我对creating selections from the elements of a list using a general number of nested loops的回答

    import string
    import math
    import random
    l = list(string.ascii_lowercase) + [str(i) for i in range(10)]
    
    new_list = []
    n = len(l)
    nCr = (math.factorial(n) / math.factorial(3) / math.factorial(n - 3))
    while len(new_list) < int(nCr):
        co = [random.randint(0, len(l) - 1) for count in range(3)]
        if len(co) == len(set(co)) and co not in new_list:
            new_list.append(co)
    final_list = []
    for x in new_list:
        combination = [q for q in l if l.index(q) in x]
        final_list.append(combination)
    
    print(sorted(final_list)) 
    
    

    列表已排序

    我无法显示输出,因为它太大了

    【讨论】:

    • 这也可以,更好地用于便携性
    【解决方案3】:
    letters = list(string.ascii_lowercase) 
    for i in letters:
        for j in letters:
            for k in letters:
                s = i + j + k
    

    's' 是迭代时得到的字符串。 您将获得所有组合按字母顺序排列。

    【讨论】:

    • 这会生成小于 3 的组合,例如 a 或 b
    猜你喜欢
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多