获取组合列表的序列号

时间:2018-03-29 07:02:32

标签: python-3.x combinations

我需要获取组合列表的序列号。这就是我写的:

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 个答案:

答案 0 :(得分:0)

您可以使用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')

答案 1 :(得分:0)

基本上你需要删除前面的'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