提问者:小点点

如何按顺序连接列表中的元素?


如何组合列表的元素以创建顺序保持不变的列表。 例如,我有一个列表a=[1,2,3],我想要一个列表b=[12,13,23],我一直在考虑这个问题,但是无法为包含3个以上元素(可能是11个)的列表找到一个合适的解决方案。现在,我已经为包含3个元素的列表硬编码了这个问题,但是我想知道一个更聪明的方法来实现这个问题。


共3个答案

匿名用户

也可以尝试IterTools.Combinations:

import itertools

a = [1, 2, 3]
print([int("".join(i)) for i in itertools.combinations("".join(map(str, a)), 2)])

结果:

[12, 13, 23]

匿名用户

作为蛮力解决方案,您可以运行2个循环

In [155]: a
Out[155]: [1, 2, 3]

In [156]: temp = []

In [160]: for i in range(len(a)):
     ...:     for j in range(i+1, len(a)):
     ...:         temp.append(int(f"{a[i]}{a[j]}"))
     ...:
     ...:

In [161]: temp
Out[161]: [12, 13, 23]

匿名用户

您可以像这样使用itertools:

import itertools
a = [1,2,3,4]

it = itertools.combinations(a, 2)
temp = []
for comb in it:
  temp.append(f"{comb[0]}{comb[1]}")

temp