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
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.
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.
next compare [6, 4, 5]
with [5,4,6
] and [7,1,2]
and the answer would be [6,5,4]
next compare [7,1,2]
with [5,4,6]
and [6, 4, 5]
and the answer would be [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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.