Union of sublists with common elementsDifference between append vs. extend list methods in PythonCombining two lists and removing duplicates, without removing duplicates in original listIs there a more elegant/optimised way I can make this connectivity algorithm?List of lists changes reflected across sublists unexpectedlyHow do I remove an element from a list by index in Python?Using LINQ to remove elements from a List<T>Getting the last element of a list in PythonFind the most common element in a listWhat is the common header format of Python files?How do I get the number of elements in a list in Python?Is there a simple way to delete a list element by value?Delete an element from a dictionaryHow to find all occurrences of an element in a list?
Should I tell management that I intend to leave due to bad software development practices?
What's the point of deactivating Num Lock on login screens?
How to draw the figure with four pentagons?
Would Slavery Reparations be considered Bills of Attainder and hence Illegal?
Twin primes whose sum is a cube
Why is consensus so controversial in Britain?
How to say in German "enjoying home comforts"
What is the word for reserving something for yourself before others do?
Will google still index a page if I use a $_SESSION variable?
Is it possible to run Internet Explorer on OS X El Capitan?
What does it mean to describe someone as a butt steak?
Is "remove commented out code" correct English?
Anagram holiday
Can I ask the recruiters in my resume to put the reason why I am rejected?
Why does Kotter return in Welcome Back Kotter
Is Lorentz symmetry broken if SUSY is broken?
How do conventional missiles fly?
Did Shadowfax go to Valinor?
What mechanic is there to disable a threat instead of killing it?
When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?
How could indestructible materials be used in power generation?
What to put in ESTA if staying in US for a few days before going on to Canada
Forgetting the musical notes while performing in concert
90's TV series where a boy goes to another dimension through portal near power lines
Union of sublists with common elements
Difference between append vs. extend list methods in PythonCombining two lists and removing duplicates, without removing duplicates in original listIs there a more elegant/optimised way I can make this connectivity algorithm?List of lists changes reflected across sublists unexpectedlyHow do I remove an element from a list by index in Python?Using LINQ to remove elements from a List<T>Getting the last element of a list in PythonFind the most common element in a listWhat is the common header format of Python files?How do I get the number of elements in a list in Python?Is there a simple way to delete a list element by value?Delete an element from a dictionaryHow to find all occurrences of an element in a list?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
Say I have for example the following nested list:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
How can I group these sublists, by getting the union of sublists which have a common element with at least another sublist within the group? So for the previous example the result should be:
[['John','Sayyed','Simon'] ,['bush','trump'],
['Sam','Suri','NewYork','Orlando','Canada']]
Thus the first two sublists are joined as they share 'John'
.
Could someone please share their valuable thoughts ?
python list networkx
|
show 1 more comment
Say I have for example the following nested list:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
How can I group these sublists, by getting the union of sublists which have a common element with at least another sublist within the group? So for the previous example the result should be:
[['John','Sayyed','Simon'] ,['bush','trump'],
['Sam','Suri','NewYork','Orlando','Canada']]
Thus the first two sublists are joined as they share 'John'
.
Could someone please share their valuable thoughts ?
python list networkx
2
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
1
create a set & union of both list contents. Convert back to list:list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings
– Jean-François Fabre♦
Dec 21 '18 at 14:08
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
1
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47
|
show 1 more comment
Say I have for example the following nested list:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
How can I group these sublists, by getting the union of sublists which have a common element with at least another sublist within the group? So for the previous example the result should be:
[['John','Sayyed','Simon'] ,['bush','trump'],
['Sam','Suri','NewYork','Orlando','Canada']]
Thus the first two sublists are joined as they share 'John'
.
Could someone please share their valuable thoughts ?
python list networkx
Say I have for example the following nested list:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
How can I group these sublists, by getting the union of sublists which have a common element with at least another sublist within the group? So for the previous example the result should be:
[['John','Sayyed','Simon'] ,['bush','trump'],
['Sam','Suri','NewYork','Orlando','Canada']]
Thus the first two sublists are joined as they share 'John'
.
Could someone please share their valuable thoughts ?
python list networkx
python list networkx
edited Dec 23 '18 at 23:12
yatu
15.6k41542
15.6k41542
asked Dec 21 '18 at 14:05
AiyazAiyaz
353
353
2
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
1
create a set & union of both list contents. Convert back to list:list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings
– Jean-François Fabre♦
Dec 21 '18 at 14:08
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
1
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47
|
show 1 more comment
2
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
1
create a set & union of both list contents. Convert back to list:list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings
– Jean-François Fabre♦
Dec 21 '18 at 14:08
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
1
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47
2
2
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
1
1
create a set & union of both list contents. Convert back to list:
list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings– Jean-François Fabre♦
Dec 21 '18 at 14:08
create a set & union of both list contents. Convert back to list:
list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings– Jean-François Fabre♦
Dec 21 '18 at 14:08
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
1
1
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47
|
show 1 more comment
4 Answers
4
active
oldest
votes
You can use networkx
for that. Generate a graph, and add your list as the graph edges using add_edges_from
. Then use connected_components
, which will precisely give you a list of sets of the connected components in the graph:
import networkx as nx
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']
G=nx.Graph()
G.add_edges_from(L)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon', 'bush', 'trump']
Update
In the case of having sublists with more than 2
elements, you can get all the length 2
combinations
from each sublist and use these as the network edges:
from itertools import combinations, chain
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
L2_nested = [list(combinations(l,2)) for l in L]
L2 = list(chain.from_iterable(L2_nested))
#[('John', 'Sayyed'), ('John', 'Simon'), ('bush', 'trump'), ('Sam', 'Suri')...
G=nx.Graph()
G.add_edges_from(L2)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon',
'bush', 'trump',
'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri']
Networkx also allows you to visualize the network with nx.draw
:
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
Details
More detailed explanation on connected components:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph
So essentially, this code creates a graph, with edges from the list, where each edge is composed by two values u,v
where u
and v
will be nodes connected by this edge.
And hence, the union of sublists with at least one sublist with a common element can be translated into a Graph Theory problem as all nodes that are reachable between each other through the existing paths.
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
add a comment |
If order is important and the list are large, you can use this two pronged method:
l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
def join(l1, l2):
mset = set(l1)
result = l1[:] # deep copy
for each in l2:
if each in mset:
continue
else:
result.append(each)
return result
To merge within the master list, you can just call the list by their rank and pop the original list:
l1 = l.pop(0)
l2 = l.pop(0)
l.insert(0, join(l1, l2))
>>> l:
[['john', 'sayyid', 'simon'], ['b', 't']]
add a comment |
To merge 2 lists:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
To be more efficient, create a set
on l1
;
add a comment |
A simple approach
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
L[0].extend([x for x in L[1] if x not in L[0]])
L.pop(1)
print(L)
See
List Comprehensions
Append vs Extend
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53886120%2funion-of-sublists-with-common-elements%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use networkx
for that. Generate a graph, and add your list as the graph edges using add_edges_from
. Then use connected_components
, which will precisely give you a list of sets of the connected components in the graph:
import networkx as nx
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']
G=nx.Graph()
G.add_edges_from(L)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon', 'bush', 'trump']
Update
In the case of having sublists with more than 2
elements, you can get all the length 2
combinations
from each sublist and use these as the network edges:
from itertools import combinations, chain
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
L2_nested = [list(combinations(l,2)) for l in L]
L2 = list(chain.from_iterable(L2_nested))
#[('John', 'Sayyed'), ('John', 'Simon'), ('bush', 'trump'), ('Sam', 'Suri')...
G=nx.Graph()
G.add_edges_from(L2)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon',
'bush', 'trump',
'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri']
Networkx also allows you to visualize the network with nx.draw
:
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
Details
More detailed explanation on connected components:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph
So essentially, this code creates a graph, with edges from the list, where each edge is composed by two values u,v
where u
and v
will be nodes connected by this edge.
And hence, the union of sublists with at least one sublist with a common element can be translated into a Graph Theory problem as all nodes that are reachable between each other through the existing paths.
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
add a comment |
You can use networkx
for that. Generate a graph, and add your list as the graph edges using add_edges_from
. Then use connected_components
, which will precisely give you a list of sets of the connected components in the graph:
import networkx as nx
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']
G=nx.Graph()
G.add_edges_from(L)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon', 'bush', 'trump']
Update
In the case of having sublists with more than 2
elements, you can get all the length 2
combinations
from each sublist and use these as the network edges:
from itertools import combinations, chain
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
L2_nested = [list(combinations(l,2)) for l in L]
L2 = list(chain.from_iterable(L2_nested))
#[('John', 'Sayyed'), ('John', 'Simon'), ('bush', 'trump'), ('Sam', 'Suri')...
G=nx.Graph()
G.add_edges_from(L2)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon',
'bush', 'trump',
'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri']
Networkx also allows you to visualize the network with nx.draw
:
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
Details
More detailed explanation on connected components:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph
So essentially, this code creates a graph, with edges from the list, where each edge is composed by two values u,v
where u
and v
will be nodes connected by this edge.
And hence, the union of sublists with at least one sublist with a common element can be translated into a Graph Theory problem as all nodes that are reachable between each other through the existing paths.
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
add a comment |
You can use networkx
for that. Generate a graph, and add your list as the graph edges using add_edges_from
. Then use connected_components
, which will precisely give you a list of sets of the connected components in the graph:
import networkx as nx
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']
G=nx.Graph()
G.add_edges_from(L)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon', 'bush', 'trump']
Update
In the case of having sublists with more than 2
elements, you can get all the length 2
combinations
from each sublist and use these as the network edges:
from itertools import combinations, chain
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
L2_nested = [list(combinations(l,2)) for l in L]
L2 = list(chain.from_iterable(L2_nested))
#[('John', 'Sayyed'), ('John', 'Simon'), ('bush', 'trump'), ('Sam', 'Suri')...
G=nx.Graph()
G.add_edges_from(L2)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon',
'bush', 'trump',
'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri']
Networkx also allows you to visualize the network with nx.draw
:
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
Details
More detailed explanation on connected components:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph
So essentially, this code creates a graph, with edges from the list, where each edge is composed by two values u,v
where u
and v
will be nodes connected by this edge.
And hence, the union of sublists with at least one sublist with a common element can be translated into a Graph Theory problem as all nodes that are reachable between each other through the existing paths.
You can use networkx
for that. Generate a graph, and add your list as the graph edges using add_edges_from
. Then use connected_components
, which will precisely give you a list of sets of the connected components in the graph:
import networkx as nx
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']
G=nx.Graph()
G.add_edges_from(L)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon', 'bush', 'trump']
Update
In the case of having sublists with more than 2
elements, you can get all the length 2
combinations
from each sublist and use these as the network edges:
from itertools import combinations, chain
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
L2_nested = [list(combinations(l,2)) for l in L]
L2 = list(chain.from_iterable(L2_nested))
#[('John', 'Sayyed'), ('John', 'Simon'), ('bush', 'trump'), ('Sam', 'Suri')...
G=nx.Graph()
G.add_edges_from(L2)
list(nx.connected_components(G))
['John', 'Sayyed', 'Simon',
'bush', 'trump',
'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri']
Networkx also allows you to visualize the network with nx.draw
:
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)
Details
More detailed explanation on connected components:
In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph
So essentially, this code creates a graph, with edges from the list, where each edge is composed by two values u,v
where u
and v
will be nodes connected by this edge.
And hence, the union of sublists with at least one sublist with a common element can be translated into a Graph Theory problem as all nodes that are reachable between each other through the existing paths.
edited Mar 21 at 21:56
answered Dec 21 '18 at 14:09
yatuyatu
15.6k41542
15.6k41542
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
add a comment |
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
1
1
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Interesting approach, please explain what this does
– Jab
Dec 21 '18 at 14:10
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
Added some explanations @jaba, hope its clearer
– yatu
Dec 21 '18 at 14:18
1
1
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
What happens if the sub-list have more than two elements?
– Daniel Mesejo
Dec 21 '18 at 14:21
1
1
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz updated with a more generic case of having sublists with more than 2 elements
– yatu
Dec 22 '18 at 9:31
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
@Aiyaz just a reminder, please let me know this helped by accepting. Also in order for future visitors to know it solved it for you. Thanks! See What should I do when someone answers my question?
– yatu
Feb 21 at 8:44
add a comment |
If order is important and the list are large, you can use this two pronged method:
l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
def join(l1, l2):
mset = set(l1)
result = l1[:] # deep copy
for each in l2:
if each in mset:
continue
else:
result.append(each)
return result
To merge within the master list, you can just call the list by their rank and pop the original list:
l1 = l.pop(0)
l2 = l.pop(0)
l.insert(0, join(l1, l2))
>>> l:
[['john', 'sayyid', 'simon'], ['b', 't']]
add a comment |
If order is important and the list are large, you can use this two pronged method:
l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
def join(l1, l2):
mset = set(l1)
result = l1[:] # deep copy
for each in l2:
if each in mset:
continue
else:
result.append(each)
return result
To merge within the master list, you can just call the list by their rank and pop the original list:
l1 = l.pop(0)
l2 = l.pop(0)
l.insert(0, join(l1, l2))
>>> l:
[['john', 'sayyid', 'simon'], ['b', 't']]
add a comment |
If order is important and the list are large, you can use this two pronged method:
l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
def join(l1, l2):
mset = set(l1)
result = l1[:] # deep copy
for each in l2:
if each in mset:
continue
else:
result.append(each)
return result
To merge within the master list, you can just call the list by their rank and pop the original list:
l1 = l.pop(0)
l2 = l.pop(0)
l.insert(0, join(l1, l2))
>>> l:
[['john', 'sayyid', 'simon'], ['b', 't']]
If order is important and the list are large, you can use this two pronged method:
l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
def join(l1, l2):
mset = set(l1)
result = l1[:] # deep copy
for each in l2:
if each in mset:
continue
else:
result.append(each)
return result
To merge within the master list, you can just call the list by their rank and pop the original list:
l1 = l.pop(0)
l2 = l.pop(0)
l.insert(0, join(l1, l2))
>>> l:
[['john', 'sayyid', 'simon'], ['b', 't']]
edited Dec 21 '18 at 14:20
answered Dec 21 '18 at 14:14
Rocky LiRocky Li
3,5611719
3,5611719
add a comment |
add a comment |
To merge 2 lists:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
To be more efficient, create a set
on l1
;
add a comment |
To merge 2 lists:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
To be more efficient, create a set
on l1
;
add a comment |
To merge 2 lists:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
To be more efficient, create a set
on l1
;
To merge 2 lists:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
To be more efficient, create a set
on l1
;
answered Dec 21 '18 at 14:31
CykerCyker
3,14863347
3,14863347
add a comment |
add a comment |
A simple approach
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
L[0].extend([x for x in L[1] if x not in L[0]])
L.pop(1)
print(L)
See
List Comprehensions
Append vs Extend
add a comment |
A simple approach
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
L[0].extend([x for x in L[1] if x not in L[0]])
L.pop(1)
print(L)
See
List Comprehensions
Append vs Extend
add a comment |
A simple approach
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
L[0].extend([x for x in L[1] if x not in L[0]])
L.pop(1)
print(L)
See
List Comprehensions
Append vs Extend
A simple approach
L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
L[0].extend([x for x in L[1] if x not in L[0]])
L.pop(1)
print(L)
See
List Comprehensions
Append vs Extend
answered Dec 21 '18 at 16:20
nandu kknandu kk
1438
1438
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53886120%2funion-of-sublists-with-common-elements%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Is the order of items in the merged list important?
– ikkuh
Dec 21 '18 at 14:07
1
create a set & union of both list contents. Convert back to list:
list(set(L[0]) | set(L[1]))
. Your example is hard to exploit. It should contain quoted strings– Jean-François Fabre♦
Dec 21 '18 at 14:08
See this post stackoverflow.com/questions/1319338/… . Can be helpful to you
– Daladier Sampaio
Dec 21 '18 at 14:09
1
The code you posted seems incomplete: are those supposed to be strings or variables? If variables, then what kind of objects are they?
– Ralf
Dec 21 '18 at 14:09
Order is not important and it contains strings.The example is not limited to L1 and l2 but there may be many lists present
– Aiyaz
Dec 21 '18 at 15:47