【问题标题】:Need string output with combination on integers需要整数组合的字符串输出
【发布时间】:2023-01-03 12:27:52
【问题描述】:

我有一本字典,以“int”为键

{12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}

我正在尝试为 12、13、14、15 的每个可能组合创建一个字符串。该字符串应该从“Gen”开始

['Gen_12_13',
 'Gen_12_14',
 'Gen_12_15',
 'Gen_13_14',
 'Gen_13_15',
 'Gen_14_15',
 'Gen_12_13_14',
 'Gen_12_13_15',
 'Gen_12_14_15',
 'Gen_13_14_15',
 'Gen_12_13_14_15']

我首先使用“组合”函数获取所有组合,然后尝试遍历它以创建“Gen”字符串。

dict_gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
all_gens = list(dict_gens.keys())
list_comb = list()
name_comb = list()
counter = 0

for item in range(2, len(all_gens)+1):
    combs = combinations(all_gens, item)
    for comb in combs:
        list_comb.append(comb)
        
for comb in list_comb:
    if counter <= len(comb):
        for comb_item in comb:
#             print(comb_item)
            name = '_' + str(comb_item)
            counter+=1
        name_comb.append('Gen'+name)

【问题讨论】:

标签: python


【解决方案1】:

itertools.combinations 部分看起来不错,但是构建最终字符串的循环看起来不必要地复杂;只需使用 str.join 将组合连接到所需的字符串中。

>>> gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
>>> from itertools import combinations
>>> ["Gen_" + "_".join(map(str, c)) for n in range(len(gens) - 1) for c in combinations(gens, n+2)]
['Gen_12_13', 'Gen_12_14', 'Gen_12_15', 'Gen_13_14', 'Gen_13_15', 'Gen_14_15', 'Gen_12_13_14', 'Gen_12_13_15', 'Gen_12_14_15', 'Gen_13_14_15', 'Gen_12_13_14_15']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2018-11-01
    • 2016-08-09
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多