[英]how to create all possible orders in a specific length from a list of strings
I have a list of strings that need to fit in 6 characters.我有一个需要容纳 6 个字符的字符串列表。 The strings can be split but the characters in the string can't be randomized.
字符串可以拆分,但字符串中的字符不能随机化。 The strings have different lengths (4 and 3 characters)
字符串具有不同的长度(4 个和 3 个字符)
I tried a few things with itertools and know how to get all possibilities but not how to get only the possibilities with a specific length requirement.我用 itertools 尝试了一些东西,并且知道如何获得所有可能性,但不知道如何仅获得具有特定长度要求的可能性。
It's ok to omit the first zero from the list entries.可以从列表条目中省略第一个零。
An example of a list:列表示例:
wordlist = ["0254", "0294", "0284", "0289", "027", "024", "026", "088"]
It would be ok to get combinations like 025427
, 254027
, 270254
, 027254
(0 and 4 of the list) and the obvious 027088
, 088027
(4 and 7 of the list) and even 272488
(4, 5 and 7 of the list)可以得到
025427
、 254027
、 270254
、 027254
(列表的 0 和 4 )和明显的027088
、 088027
(列表的 4 和 7 )甚至272488
(列表的 4 、 5 和 7 )这样的组合
I think the solution lies in itertools in combination with something else.我认为解决方案在于 itertools 与其他东西的结合。
Just use a standard double loop and check if you need/can remove zeros to get the desired length只需使用标准双循环并检查您是否需要/可以删除零以获得所需的长度
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
This will give you all possible combinations (including matching elements with themselves)这将为您提供所有可能的组合(包括与自身匹配的元素)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.