【问题标题】:how to create all possible orders in a specific length from a list of strings如何从字符串列表中创建特定长度的所有可能订单
【发布时间】:2022-07-07 21:55:05
【问题描述】:

我有一个需要 6 个字符的字符串列表。字符串可以拆分,但字符串中的字符不能随机化。字符串有不同的长度(4 个和 3 个字符)

我用 itertools 做了一些尝试,知道如何获得所有可能性,但不知道如何仅获得具有特定长度要求的可能性。

可以省略列表条目中的第一个零。

列表示例:

wordlist = ["0254", "0294", "0284", "0289", "027", "024", "026", "088"]

可以得到025427254027270254027254(列表中的 0 和 4)以及明显的 027088088027(列表中的 4 和 7)这样的组合列表)甚至272488(列表中的第4、5和7)

我认为解决方案在于将 itertools 与其他东西结合起来。

【问题讨论】:

  • 使用标准双循环。对于每个元素迭代所有元素并连接,需要删除前导 0
  • 谢谢@S 那不会形成三重循环吗?因为删除前导 0 是可选的。

标签: python itertools


【解决方案1】:

只需使用标准双循环

combinations = []
for i in wordlist:
    for j in wordlist:
        if len(i) == 4 and len(j) == 4:  # remove both zeros
            combinations.append(i[1:] + j[1:]) 
        elif len(i) == 3 and len(j) == 3:
            combinations.append(i + j)  # dont remove any zero
        else:
            combinations.append(i[1:] + j)  # remove first element zero
            combinations.append(i + j[1:])  # remove second element zero

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    相关资源
    最近更新 更多