如何在Python中根据条件将元组拆分为子元组

  • 本文关键字:元组 拆分 条件 Python python
  • 更新时间 :
  • 英文 :


我有一个类似[1,2,1,1,2,3,3]的列表。我想根据将这个元组分为子元组

[1,2,1,1] [2,1,1,2] [3,3]

因此,分离向量的条件是元组的第一个数最后一次重复时。

我该怎么做?

您可以读取元素,并在执行过程中收集每个元素的第一个和最后一个索引。

然后相应地划分你的列表:

l = [1,2,1,1,2,3,3]
d = {}
for i, v in enumerate(l): # for each value in the input
if v not in d:      # if the value was not yet seen
d[v] = [i, i+1] # record its position and the next in d
else:               # if the value was already seen
d[v][1] = i+1   # update its last position (+1 for inclusive slicing)
out = {k: l[slice(*v)] for k,v in d.items()}

输出(此处为字典(:

{1: [1, 2, 1, 1],
2: [2, 1, 1, 2],
3: [3, 3]}

一个简单的程序:

l = (1,2,1,1,2,3,3)
r=[]
for i in set(l):
li = len(l) - 1 - l[::-1].index(i)   #last index of item
lf = l.index(i)                      #first index of item
r.append((l[lf:li+1]))
print(r)

结果:

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

最新更新