代码之家  ›  专栏  ›  技术社区  ›  Hüseyin

获取组合列表的序列号

  •  -2
  • Hüseyin  · 技术社区  · 7 年前

    我需要得到组合列表的序列号。下面是我写的:

    import itertools
    
    my_list = ["a1","a2","a3","a4"]
    
    for i in itertools.combinations(my_list, 2):
        print(i)
    
    output:
    ('a1', 'a2')
    ('a1', 'a3')
    ('a1', 'a4')
    ('a2', 'a3')
    ('a2', 'a4')
    ('a3', 'a4')
    

    但我希望输出像

    ('1', '2')
    ('1', '3')
    ('1', '4')
    ('2', '3')
    ('2', '4')
    ('3', '4')
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Patrick Artner    7 年前

    因此,基本上您需要删除 'a' 在它前面:

    import itertools
    
    my_list = ["a1","a2","a3","a4"]
    
    # use only the number as string, discard the 'a'
    myListNoA = [x[1] for x in my_list]
    
    for i in itertools.combinations(myListNoA, 2):
        print(i)
    

    输出:

    ('1', '2')
    ('1', '3')
    ('1', '4')
    ('2', '3')
    ('2', '4')
    ('3', '4')
    

    编辑:

    您的评论表明,在原始列表中使用索引会更好:

    import itertools
    
    my_list = ["istanbul","izmir","ankara","samsun"]
    
    # get a combination of index-values into your original list
    combin =list( itertools.combinations(range(len(my_list)), 2))
    print(combin)
    

    输出:

    [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
    

    通过索引到原始列表数据来打印组合:

    # print all combinations:
    print( "Flights:" )
    for a,b in combin: # tuple decomposition  (0,1) -- a=0, b=1 etc.
        print(my_list[a],  my_list[b], sep =" to ")
    

    输出:

    Flights:
    istanbul to izmir
    istanbul to ankara
    istanbul to samsun
    izmir to ankara
    izmir to samsun
    ankara to samsun
    
        2
  •  0
  •   Rakesh    7 年前

    您可以使用 regex 提取 int 价值观

    例如:

    import itertools
    import re
    my_list = ["a1","a2","a3","a4"]
    for i in itertools.combinations(my_list, 2): 
        print(tuple(re.findall("\d+", "-".join(i))))
    

    输出:

    ('1', '2')
    ('1', '3')
    ('1', '4')
    ('2', '3')
    ('2', '4')
    ('3', '4')