473,910 Members | 6,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

merging of lists

32 New Member
Expand|Select|Wrap|Line Numbers
  1. aList = [1,2,3,4,5]
  2. bList = [4,5,6,7,8]
  3. cList = [7,8,9,10,11]
  4.  
  5. dList = [100,200,300]
  6. eList = [100,400,500]
  7.  
  8. list1 = list(set(aList) | set(bList) |set(cList))
  9. list2 = list(set(dList) | set(eList))
  10.  
  11. print list1,list2
  12.  
I have "n" lists each having a set of integer values. I would like to merge the list and get resulant or resultants list if there is at least one element that is common in both the list.

In the above sample code, I see aList and bList have common elements and similarly bList and cList. Hence I obtained list1 merging this. Similary dList and eList are having common element and hence merged dList and eList as list2.

I would like to know how to write a consice code looping over each list to obtain the resultant(s) list.

Thanks in advance.

SKN
Aug 16 '07 #1
14 2397
ghostdog74
511 Recognized Expert Contributor
Expand|Select|Wrap|Line Numbers
  1. aList = [1,2,3,4,5]
  2. bList = [4,5,6,7,8]
  3. cList = [7,8,9,10,11]
  4.  
  5. dList = [100,200,300]
  6. eList = [100,400,500]
  7.  
  8. list1 = list(set(aList) | set(bList) |set(cList))
  9. list2 = list(set(dList) | set(eList))
  10.  
  11. print list1,list2
  12.  
I have "n" lists each having a set of integer values. I would like to merge the list and get resulant or resultants list if there is at least one element that is common in both the list.

In the above sample code, I see aList and bList have common elements and similarly bList and cList. Hence I obtained list1 merging this. Similary dList and eList are having common element and hence merged dList and eList as list2.

I would like to know how to write a consice code looping over each list to obtain the resultant(s) list.

Thanks in advance.

SKN
Expand|Select|Wrap|Line Numbers
  1. >>> set(aList+bList+cList)
  2. set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
  3.  
Aug 16 '07 #2
bartonc
6,596 Recognized Expert Expert
Yes. 5.7.1 Set Objects come in very handy. Thanks, GD.
Aug 16 '07 #3
hidrkannan
32 New Member
The problem is to identify the lists that have common elements programatically . I have shown as an example that shows aList, bList, & cList have common elements and hence merged as list1.

Actually, I need to loop over and compare 2 lists and if have common elements merge as one list, and continue through the lists again. I am looking for a concise code to get this.

Thanks
SKN
Aug 16 '07 #4
bartonc
6,596 Recognized Expert Expert
The problem is to identify the lists that have common elements programatically . I have shown as an example that shows aList, bList, & cList have common elements and hence merged as list1.

Actually, I need to loop over and compare 2 lists and if have common elements merge as one list, and continue through the lists again. I am looking for a concise code to get this.

Thanks
SKN
This will compare the 0th to the 1st, the 1st to the 2nd and the 2nd to the 0th, in that order:
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [1,2,3,4,5]
  2. >>> bList = [4,5,6,7,8]
  3. >>> cList = [7,8,9,10,11]
  4. >>> allLists = [aList, bList, cList]
  5. >>> stopat = len(allLists) - 1
  6. >>> for i, thisList in enumerate(allLists):
  7. ...     nextIndex = (i + 1, 0)[i == stopat]
  8. ...     result = set(thisList).intersection(set(allLists[nextIndex]))
  9. ...     if result:
  10. ...         print result
  11. ...         
  12. set([4, 5])
  13. set([8, 7])
  14. >>> 
Aug 16 '07 #5
hidrkannan
32 New Member
This will compare the 0th to the 1st, the 1st to the 2nd and the 2nd to the 0th, in that order:
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [1,2,3,4,5]
  2. >>> bList = [4,5,6,7,8]
  3. >>> cList = [7,8,9,10,11]
  4. >>> allLists = [aList, bList, cList]
  5. >>> stopat = len(allLists) - 1
  6. >>> for i, thisList in enumerate(allLists):
  7. ...     nextIndex = (i + 1, 0)[i == stopat]
  8. ...     result = set(thisList).intersection(set(allLists[nextIndex]))
  9. ...     if result:
  10. ...         print result
  11. ...         
  12. set([4, 5])
  13. set([8, 7])
  14. >>> 

I can substitute union in place of intersection to get the result. But is not still sufficient to get the desired result completely of getting two list as shown in my original posting.

Need your help.

Thanks
SKN
Aug 16 '07 #6
bartonc
6,596 Recognized Expert Expert
I can substitute union in place of intersection to get the result. But is not still sufficient to get the desired result completely of getting two list as shown in my original posting.

Need your help.

Thanks
SKN
Yep. You are right about that. I missed part of your spec and going sequentially doesn't quite to a complete job. Please post some of your work so that we may see where you have gotten on improving on my post. Thanks.
Aug 16 '07 #7
hidrkannan
32 New Member
Expand|Select|Wrap|Line Numbers
  1. aList = [1,2,3,4,5]
  2. bList = [4,5,6,7,8]
  3. cList = [7,8,9,10,11]
  4. dList = [100,200,300,400]
  5. eList = [100,600,700]
  6. allLists = [aList, bList, cList,dList,eList]
  7. flag = 1
  8. resultList = []
  9. while (flag == 1):
  10.     listCount = len(allLists)
  11.     count = 0
  12.     removeList = []
  13.     for i in range(0,listCount-1):        
  14.         if len((set(allLists[0]) & set(allLists[i+1]))) > 0:
  15.             count = count + 1
  16.             set(allLists[0]).union(set(allLists[i+1]))
  17.             removeList.append(allLists[i+1])
  18.             count = count + 1
  19.             allLists[0] = list(set(allLists[0]).union(set(allLists[i+1])))            
  20.     if len(allLists):
  21.         resultList.append(allLists[0])
  22.         allLists.remove(allLists[0])
  23.     for tempList in removeList:
  24.         if tempList in allLists:
  25.             allLists.remove(tempList)
  26.     if count == 0:
  27.         flag = 0
  28. print resultList
  29.  

The above code does the job, but I feel it is lengthy and rounabout...

Thanks
SKN
Aug 17 '07 #8
bartonc
6,596 Recognized Expert Expert
Expand|Select|Wrap|Line Numbers
  1. aList = [1,2,3,4,5]
  2. bList = [4,5,6,7,8]
  3. cList = [7,8,9,10,11]
  4. dList = [100,200,300,400]
  5. eList = [100,600,700]
  6. allLists = [aList, bList, cList,dList,eList]
  7. flag = 1
  8. resultList = []
  9. while (flag == 1):
  10.     listCount = len(allLists)
  11.     count = 0
  12.     removeList = []
  13.     for i in range(0,listCount-1):        
  14.         if len((set(allLists[0]) & set(allLists[i+1]))) > 0:
  15.             count = count + 1
  16.             set(allLists[0]).union(set(allLists[i+1]))
  17.             removeList.append(allLists[i+1])
  18.             count = count + 1
  19.             allLists[0] = list(set(allLists[0]).union(set(allLists[i+1])))            
  20.     if len(allLists):
  21.         resultList.append(allLists[0])
  22.         allLists.remove(allLists[0])
  23.     for tempList in removeList:
  24.         if tempList in allLists:
  25.             allLists.remove(tempList)
  26.     if count == 0:
  27.         flag = 0
  28. print resultList
  29.  

The above code does the job, but I feel it is lengthy and rounabout...

Thanks
SKN
Here it is a bit simplified. But, if you'll notice, with the order of allLists rearranged, the algorithm is broken. I'm working on a fix, though.
Expand|Select|Wrap|Line Numbers
  1. aList = [1, 2, 3, 4, 5]
  2. bList = [4, 5, 6, 7, 8]
  3. cList = [7, 8, 9, 10, 11]
  4. dList = [100, 200, 300, 400]
  5. eList = [100, 600, 700]
  6. allLists = [dList, cList, aList, bList, eList]
  7.  
  8.  
  9. resultList = []
  10. while allLists:
  11.     listCount = len(allLists)
  12.     removeList = []
  13.     for i in range(listCount - 1):
  14.         if (set(allLists[0]) & set(allLists[i+1])):
  15.             removeList.append(allLists[i+1])
  16.  
  17.             allLists[0] = list(set(allLists[0]).union(set(allLists[i+1])))
  18.  
  19.     if allLists:
  20.         tempList = allLists.pop(0)
  21.         resultList.append(tempList)
  22.  
  23.     for tempList in removeList:
  24.         if tempList in allLists:
  25.             allLists.remove(tempList)
  26.  
  27. print resultList
[[400, 600, 100, 200, 700, 300], [4, 5, 6, 7, 8, 9, 10, 11], [1, 2, 3, 4, 5]]
Aug 17 '07 #9
bartonc
6,596 Recognized Expert Expert
Here it is a bit simplified. But, if you'll notice, with the order of allLists rearranged, the algorithm is broken. I'm working on a fix, though.
Expand|Select|Wrap|Line Numbers
  1. aList = [1, 2, 3, 4, 5]
  2. bList = [4, 5, 6, 7, 8]
  3. cList = [7, 8, 9, 10, 11]
  4. dList = [100, 200, 300, 400]
  5. eList = [100, 600, 700]
  6. allLists = [dList, cList, aList, bList, eList]
  7.  
  8.  
  9. resultList = []
  10. while allLists:
  11.     listCount = len(allLists)
  12.     removeList = []
  13.     for i in range(listCount - 1):
  14.         if (set(allLists[0]) & set(allLists[i+1])):
  15.             removeList.append(allLists[i+1])
  16.  
  17.             allLists[0] = list(set(allLists[0]).union(set(allLists[i+1])))
  18.  
  19.     if allLists:
  20.         tempList = allLists.pop(0)
  21.         resultList.append(tempList)
  22.  
  23.     for tempList in removeList:
  24.         if tempList in allLists:
  25.             allLists.remove(tempList)
  26.  
  27. print resultList
[[400, 600, 100, 200, 700, 300], [4, 5, 6, 7, 8, 9, 10, 11], [1, 2, 3, 4, 5]]
Just to show you my thinking: Here is a function that is just a bit simpler than the last and still works the same. Eventually this will become a recursive function...
Expand|Select|Wrap|Line Numbers
  1. def ListUnionFinder(someLists, aList = []):
  2.     resultList = []
  3.     while someLists:
  4.         tempList = someLists.pop(0)
  5.         listCount = len(someLists)
  6.         removeList = []
  7.         for i in range(listCount - 1):
  8.             if (set(tempList) & set(someLists[i+1])):
  9.                 removeList.append(someLists[i+1])
  10.  
  11.                 tempList = list(set(tempList).union(set(someLists[i+1])))
  12.  
  13.         resultList.append(tempList)
  14.  
  15.         for tempList in removeList:
  16.             if tempList in someLists:
  17.                 someLists.remove(tempList)
  18.  
  19.     print resultList
  20.  
  21. ListUnionFinder(allLists)
Aug 17 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

24
3986
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = s2 = s3 = for value in ???(s1, s2, s3):
3
1895
by: Patrick | last post by:
I have got 2 XML documents, both of which conform to the same XSD Schema, which define possible optional elements. The 2 XML documents contain 2 disjoint set of XML elements. What is the best, easiest, most efficient way of merging the 2 XML Documents? Can I use DataSet.Merge() facility in ADO.NET?? Any pre-requisites? Any other suggestions?
1
4969
by: svdh | last post by:
I have posed a question last saturday and have advanced alot in the meantime. But I am still not there Problem is that I try to merging various fields from various tables in one document in Word 1. Query..I want to keep the fields seperatred. I do not want to sent on field with all accumulated languages from one person to Word. Each language should appear in the document in a separate cell Cross tables are not delivering the result I...
2
1722
by: teresaalmond | last post by:
I routinely have to qry several databases and combine the records for a mailing list. In all of the tables the fiedl names are different. For example: FName First name and FirstName Right not I have append queries, 1 for each list I bring in, to append to a main table. I would like to have one query or process that will process assorted different lists and append the correct fields to the main table. I also have a qry for each list...
15
1486
by: PRadyut | last post by:
In this code it throws a runtime error on a code access violation . On the line z->data=p->data; while (p!=NULL && q!=NULL) { if (*s==NULL) {
3
6558
by: ptrSriram | last post by:
Can someone help me with an algorithm to merge two binary search trees. One method I thought of was to flatten both the trees into sorted lists(inorder traversal),merge those two sorted lists, and build a binary search tree from the new list. But this seems to be expensive in terms of space. Can this be done more efficiently ? Please help me.
9
4581
by: SMB | last post by:
I have two lists of data like the following: LIST1 , ] LIST2 , 'label': 'First Name', 'width': 0L, 'separator': ',', 'height': 0L, 'type': 2L, 'order': 1L}, {'code': 14L, 'name': 'Last Name', 'value': , 'label': 'Last Name', 'width': 0L, 'separator': ',', 'height': 0L, 'type': 2L, 'order': 2L},
14
4038
by: etal | last post by:
Here's an algorithm question: How should I efficiently merge a collection of mostly similar lists, with different lengths and arbitrary contents, while eliminating duplicates and preserving order as much as possible? My code: def merge_to_unique(sources): """Merge the unique elements from each list in sources into new list.
4
2424
by: v13tn1g | last post by:
so basically i've written most of the code the only problem that i'm having is that the output that it gives me will not return a key with a different type. It will either return me keys with only int, or only str..for example def merge_dictionaries(d1, d2): '''Return a dictionary that is the result of merging the two given dictionaries. In the new dictionary, the values should be lists. If a key is in both of the given...
0
11349
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
11055
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10541
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9727
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8099
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7250
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5939
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6142
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3360
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.