[英]python list of lists common elements iteration
list= [[5, 4, 6], [6, 4, 5], [7, 1, 2]]
I have the above list, I want to compare every list index like [5,4,6]
with [6,4,5]
and [7,1,2]
ie with every other list index我有上面的列表,我想将[5,4,6]
之类的每个列表索引与[6,4,5]
和[7,1,2]
即每个其他列表索引进行比较
and for output: if there exist any common elements between 2 indexes in comparision then I want to output in a format "the first element of each index" along with any common elements in the index.对于 output:如果在比较中 2 个索引之间存在任何共同元素,那么我希望 output 格式为“每个索引的第一个元素”以及索引中的任何共同元素。
answer for this iteration would be [5,4,6] as 5 is the first element of the index in comparison, 6 is the first element of the index in comparison, 4 is the common element.此迭代的答案将是 [5,4,6],因为 5 是比较索引的第一个元素,6 是比较索引的第一个元素,4 是公共元素。
next compare [6, 4, 5]
with [5,4,6
] and [7,1,2]
and the answer would be [6,5,4]接下来将[6, 4, 5]
与[5,4,6
] 和[7,1,2]
进行比较,答案将是 [6,5,4]
next compare [7,1,2]
with [5,4,6]
and [6, 4, 5]
and the answer would be [7]
接下来将[7,1,2]
与[5,4,6]
和[6, 4, 5]
进行比较,答案将是[7]
Please help, I have been trying for really long.请帮忙,我已经尝试了很长时间。
basically I want every list index to check for common elements with every other list index and if 2 list indexes have anything in common I want to get a new output list with the first element of both list indexes and common elements基本上我希望每个列表索引与其他所有列表索引检查公共元素,如果 2 个列表索引有任何共同点,我想获得一个新的 output 列表,其中包含列表索引和公共元素的第一个元素
final output= [[5,6,4],[6,5,4],[7]]
myL = [[5, 4, 6], [6, 4, 5], [7, 1, 2]]
newLi = []
for i in range(len(myL)):
tmpLi = []
firstList = myL[i]
for a in range(len(myL)):
if a != i:
secondList = myL[a]
inCommon = set(firstList).intersection(secondList)
if len(inCommon) != 0:
tmpLi.append(firstList[0])
tmpLi.append(secondList[0])
for b in inCommon:
if b not in tmpLi:
tmpLi.append(b)
if len(tmpLi) == 0:
tmpLi.append(firstList[0])
newLi.append(tmpLi)
print(newLi)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.