Combining elements of list of lists by index
You can do:
do.call(Map, c(c, lst))
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]]
combining elements in a list of lists in R
Another base R option using paste
do.call(paste, c(data.frame(t(list2DF(samples_ID))), sep = "_"))
or
do.call(paste, data.frame(do.call(rbind, samples_ID)), sep = "_"))
join list of lists in python
import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
Merge lists with same first element in list of lists
Try this:
d = {}
for key, value in a:
if key not in d.keys():
d[key] = [key]
d[key].append(value)
result = list(d.values())
Merge python list by specific indexes
Here's an implementation using groupby
:
import itertools
x = ["captain:", "robot", "alpha", "beta:", "gama", "delta:", "fighter", "test", "exp"]
new_list = []
for key, group in itertools.groupby(x, key = lambda string: string.endswith(':')):
if key: # in case you happen to consecutive values that end in a colon
new_list += list(group)
else: # these elements do not end in a colon
new_list.append(', '.join(group))
print(new_list)
# ['captain:', 'robot, alpha', 'beta:', 'gama', 'delta:', 'fighter, test, exp']
Here, the grouping key checks to see if the item ends in a ":"
, if it does, key
is True
, otherwise it is False
. If consecutive values of key
are the same, they are put in the same group. Thus, any number of elements following a string containing a colon will be grouped together.
Merge elements in list of lists
If you don't want to write a loop you can use map
and str.join
>>> list(map(''.join, A))
['baaaa', 'baaaa']
However, the loop using a list comprehension is almost as short to write, and I think is clearer:
>>> [''.join(e) for e in A]
['baaaa', 'baaaa']
For each element in list of lists, merge with corresponding value in a separate flat list
Here is a solution you can give it a try,
lst1 = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
lst2 = ['x', 'y', 'z']
print(
[[ii + j for ii in i] for i, j in zip(lst1, lst2)]
)
[['ax', 'bx', 'cx'], ['ay', 'by', 'cy'], ['az', 'bz', 'cz']]
Related Topics
Ggplot2: Geom_Text() with Facet_Grid()
Why Is Stat = "Identity" Necessary in Geom_Bar in Ggplot
Texture in Barplot for 7 Bars in R
Problems Using Foreach Parallelization
How to Change the Na Color from Gray to White in a Ggplot Choropleth Map
Dynamic Height and Width for Knitr Plots
How to Get Parameters from Config File in R Script
How to Display Widgets Inline in Shiny
How to Convert Date and Time from Character to Datetime Type
Colorize Clusters in Dendogram with Ggplot2
Plotting Multiple Curves Same Graph and Same Scale
Install R Packages from Github Downloading Master.Zip
R: Using Rgl to Generate 3D Rotatable Plots That Can Be Viewed in a Web Browser