Combine/merge lists by elements names (list in list)
Inspired by josilber's answer, here we do not hard-code the length of the sublists and use lapply
to create them in the result:
keys <- unique(c(names(l.1), names(l.2)))
setNames(lapply(keys, function(key) {
l1 <- l.1[[key]]
l2 <- l.2[[key]]
len <- max(length(l1), length(l2))
lapply(seq(len), function(i) c(l1[[i]], l2[[i]]))
}),
keys)
Combine/merge lists by elements names (list in list in list)
You just need to use lapply
two more times with user-defined functions:
keys <- unique(unlist(lapply(l.new, names)))
l2 <- setNames(lapply(keys, function(key) {
len <- max(unlist(lapply(l.new, function(x) length(x[[key]]))))
lapply(seq(len), function(i) unlist(lapply(l.new, function(x) x[[key]][[i]])))
}), keys)
all.equal(l, l2)
# [1] TRUE
Combine/merge lists by elements names
You can do:
keys <- unique(c(names(lst1), names(lst2)))
setNames(mapply(c, lst1[keys], lst2[keys]), keys)
Generalization to any number of lists would require a mix of do.call
and lapply
:
l <- list(lst1, lst2, lst1)
keys <- unique(unlist(lapply(l, names)))
setNames(do.call(mapply, c(FUN=c, lapply(l, `[`, keys))), keys)
combine list elements based on element names
sapply(unique(names(L1)), function(x) unname(unlist(L1[names(L1)==x])), simplify=FALSE)
$F01
[1] 1 2 3 4 5 6 7 8 9
$F02
[1] 10 20 30 40 50
How to merge elements of two lists at the same index in Python?
One way to do this is to zip the input lists then add them:
a = [['a', 1], ['b', 2], ['c', 3]]
b = [10, 20, 30]
c = [x+[y] for x, y in zip(a, b)]
print(c) # -> [['a', 1, 10], ['b', 2, 20], ['c', 3, 30]]
join list of lists in python
import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
R merge two lists into one, drawing elements from each list alternatively
Using Map
append the corresponding list
elements of 's1' and 's2' as a list
and then with do.call(c
, flatten the nested list to a list of depth 1.
do.call(c, Map(list, s1, s2))
Or another option is to rbind
the list
elements into a matrix
and remove the dim
attributes with c
c(rbind(s1, s2))
Merge lists that share common elements
You can see your list as a notation for a Graph, ie ['a','b','c']
is a graph with 3 nodes connected to each other. The problem you are trying to solve is finding connected components in this graph.
You can use NetworkX for this, which has the advantage that it's pretty much guaranteed to be correct:
l = [['a','b','c'],['b','d','e'],['k'],['o','p'],['e','f'],['p','a'],['d','g']]
import networkx
from networkx.algorithms.components.connected import connected_components
def to_graph(l):
G = networkx.Graph()
for part in l:
# each sublist is a bunch of nodes
G.add_nodes_from(part)
# it also imlies a number of edges:
G.add_edges_from(to_edges(part))
return G
def to_edges(l):
"""
treat `l` as a Graph and returns it's edges
to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]
"""
it = iter(l)
last = next(it)
for current in it:
yield last, current
last = current
G = to_graph(l)
print connected_components(G)
# prints [['a', 'c', 'b', 'e', 'd', 'g', 'f', 'o', 'p'], ['k']]
To solve this efficiently yourself you have to convert the list into something graph-ish anyways, so you might as well use networkX from the start.
how can I combine list elements inside list based on element value?
There is a differnet way to do it using groupby
function from itertools
. Also there are ways to convert your dict to a list also. It totally depends on what you want.
from itertools import groupby
lis = [['steve','reporter','12','34','22','98'],['megan','arch','44','98','32','22'],['jack','doctor','80','32','65','20'],['steve','dancer','66','31','54','12']]
lis.sort(key = lambda x: x[0])
output = []
for name , groups in groupby(lis, key = lambda x: x[0]):
temp_list = [name]
for group in groups:
temp_list.extend(group[1:])
output.append(temp_list)
print(output)
OUTPUT
[['jack', 'doctor', '80', '32', '65', '20'], ['megan', 'arch', '44', '98', '32', '22'], ['steve', 'reporter', '12', '34', '22', '98', 'dancer', '66', '31', '54', '12']]
Related Topics
How to Create a "Macro" for Regressors in R
Cowplot Made Ggplot2 Theme Disappear/How to See Current Ggplot2 Theme, and Restore the Default
How to Use Functions in One R Package Masked by Another Package
Using Row-Wise Column Indices in a Vector to Extract Values from Data Frame
Add Line Break to Axis Labels and Ticks in Ggplot
How to Group My Date Variable into Month/Year in R
Change Both Legend Titles in a Ggplot with Two Legends
Showing String in Formula and Not as Variable in Lm Fit
How to Fix Corrupted Dates in R
What Are the Differences Between Community Detection Algorithms in Igraph
What Is the Significance of the New Reference Classes
Merging Two Columns into One in R
Check Whether Values in One Data Frame Column Exist in a Second Data Frame
Use Grepl to Search Either of Multiple Substrings in a Text
How to Scrape Tables Inside a Comment Tag in HTML with R