首页 > 解决方案 > 如何在不删除python中的元素的情况下更改相邻列表中相同元素的出现?

问题描述

我有两个列表 list1=['A','B','C'] list2=['1','2','3'] 我需要一个长度为 'n的长列表(由这两个列表组合而成) ' 没有

  1. 任何同一对连续 [' A1 ',' A1 ','C3',' B2 ',' B2 ',.....]
  2. list1 的任何相同元素连续 [' A 1',' A 2',' A 3',' B 1',' B 2',.......]
  3. list2 的任何相同元素连续 ['A 1 ','B 1 ','C 1 ',' A 2',' B 2',.......]

我希望组合列表的元素以任何顺序排列,但彼此之间没有重复。换句话说,就像这个例子一样,['A1','B2','C3','A2','B3','C1','A3','B1','C2','A1 ','B2','C3'......]

有人可以帮帮我吗。自2天以来,我一直在寻找答案。

编辑:

我尝试了 itertools 方法产品。

newlist = [ n[0]+n[1] for n in list(itertools.product(list1,list2))]

#这给出了我需要的元素的确切排列,但不是我希望的顺序。

新列表 = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']

#然后,我使用了嵌套循环,

#将newlist中的连续对元素交换为ind,n in enumerate(newlist): while n == newlist[ind-1]: for ind,n in enumerate(newlist): while n == newlist[ind-1] : newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

#将newlist中的连续list1元素交换为ind,n in enumerate(newlist): while n[0] == newlist[ind-1][0]: for ind,n in enumerate(newlist): while n[0 ] == newlist[ind-1][0]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

#将newlist中的连续list2元素交换为ind,n in enumerate(newlist): while n[1] == newlist[ind-1][1]: for ind,n in enumerate(newlist): while n[1 ] == newlist[ind-1][1]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

显然,它适用于超过 3 个元素的列表。但不适用于长度分别为 3 和 2 的列表。

标签: pythondata-structures

解决方案


#Join the given list
list(map("".join,(zip(["A", "B", "C"], ["1","2","3"]))))

# Given your list
l3=["A1","B1","C1","A2","B2"]
l2=["A1","A2","A3","B1","B2"]
l=["A1","A1","C3","B2","B2"]

# set() data structure ensure no duplicate
list(set(l))+list(set(l2))+list(set(l3))

# output should be:
# ['B2', 'C3', 'A1', 'B2', 'A3', 'A2', 'B1', 'A1', 'C1', 'B2', 'A2', 'B1', 'A1']

希望这有帮助。


推荐阅读