Replicate a list to create a list-of-lists
I think this has to do with rep behavior, you want to nest before you rep:
rep(list(fred),5)
The str
output:
List of 5
$ :List of 2
..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ name : chr "squash"
$ :List of 2
..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ name : chr "squash"
$ :List of 2
..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ name : chr "squash"
$ :List of 2
..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ name : chr "squash"
$ :List of 2
..$ happy: int [1:10] 1 2 3 4 5 6 7 8 9 10
..$ name : chr "squash"
How to copy a list of lists in Python?
As quamrana mentions, you can use deepcopy
.
import copy
a = [[1,2],[3,4]]
b = copy.deepcopy(a)
Taken from here.
Copying structure of a list of list to a flat list?
The following approach will work for arbitrarily nested lists, and doesn't require a deep copy nor an inefficient pop
from the end of the list, making this version linear on the total number of items, instead of quadratic:
def structured_replace(values, nested):
it = iter(values)
def _helper(nested):
return [
_helper(item) if isinstance(item, list) else next(it)
for item in nested
]
return _helper(nested)
a, b, c, d, e = "abcde"
p, q, r, s, t = "pqrst"
l1 = [a,b,c,d,e]
l2 = [[p,q],[r,s,t]]
print(structured_replace(l1, l2))
Also, just for fun, here's an iterative solution:
def structured_replace(values, nested):
it = iter(values)
top_result = []
stack = [(nested, top_result)]
while stack:
item, result = stack.pop()
if isinstance(item, list):
subresult = []
result.append(subresult)
for sub in reversed(item):
stack.append((sub, subresult))
else:
result.append(next(it))
return top_result[0]
Also, here's a breadth-first approach, which we can modify the iterative approach easily and use the standard queue-based approach:
def structured_replace_breadth_first(values, nested):
from collections import deque
it = iter(values)
top_result = []
stack = deque([(nested, top_result)])
while stack:
item, result = stack.popleft()
if isinstance(item, list):
subresult = []
result.append(subresult)
for sub in item:
stack.append((sub, subresult))
else:
result.append(next(it))
return top_result[0]
For the differences:
In [5]: structured_replace('abcdefg', [[1, 2], 3, [4, [5, 6], 7]])
Out[5]: [['a', 'b'], 'c', ['d', ['e', 'f'], 'g']]
In [6]: structured_replace_level_first('abcdefg', [[1, 2], 3, [4, [5, 6], 7]])
Out[6]: [['b', 'c'], 'a', ['d', ['f', 'g'], 'e']]
How to convert a list into list of lists?
You can use list comprehension with range
to get x
number of element. For example you want 4 elements use
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
out = [l[i: i+4] for i in range(0, len(l), 4)]
print(out)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
How to create a new list of lists from a list of lists in Haskell?
You need to determine the length of the strings. You can do this for example with a lambda expression, so then the mapping looks like:
func :: [String] -> [String]
func mylines = map (\x -> … ) linesOfFiles ++ replicate (5-length mylines) (replicate 5' ')
where x
is thus string that will be mapped, and …
is an expression to what that value is mapped. I leave filling in …
as an exercise.
Usually it is better not to work with length
: length
takes linear time, and for infinite lists, this will even get the program into an infinite loop.
You can work with recursion to perform padding, something like:
padding :: Int -> a -> [a] -> [a]
padding 0 _ xs = …
padding n x [] = …
padding n x (x:xs) = …
join list of lists in python
import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))
convert a list of lists to a list of strings
since you have a list of list and string in it and you want list of string with no duplicate present.
create a resultant list, and then iterate through the parent list and check the type of each object, if it of type list then iterate through the sublist and check that string in sublist is present in the resultant list or not, if present then ignore else if not present then add it to list, same goes for the parent list iterate when it is not of type list.
res = [[u'xyza'], [u'xyzb'], [u'xyzc', u'xyzd', u'xyze', u'xyzf', u'xyzg', u'xyzh'], u'xyzd', [u'xyza'],[u'xyxv']]
result =[]
for i in res:
if isinstance(i, list):
for j in i:
if j not in result:
result.append(j)
else:
if i not in result:
result.append(i)
print(result)
output:
['xyza', 'xyzb', 'xyzc', 'xyzd', 'xyze', 'xyzf', 'xyzg', 'xyzh','xyxv']
if you want to make it little faster, then instead of result
as list , you can create it as a dictionary and without checking the condtition if string already present or not, you just update the dictionary and once you iterate through whole list, convert the dictionary keys to list and that is your answer.
Python copy a list of lists
From the docs for the copy
module:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
When you call regular copy.copy()
you are performing a shallow copy. This means that in a case of a list-of-lists, you will get a new copy of the outer list, but it will contain the original inner lists as its elements. Instead you should use copy.deepcopy()
, which will create a new copy of both the outer and inner lists.
The reason that you didn't notice this with your first example of using copy([1,2])
is that the primitives like int
are immutable, and thus it is impossible to change their value without creating a new instance. If the contents of the list had instead been mutable objects (like lists, or any user-defined object with mutable members), any mutation of those objects would have been seen in both copies of the list.
Create list of lists filled with the same values
l1 = [[False] * n] * m
# I assume this is what you did, since
# [False * 3] == [0], and not [False, False, False]
takes the same list
instance [False * n]
m times. Changing one reference to said instance will affect all references. Use a comprehension instead to create independent lists:
l1 = [[False] * n for _ in range(m)]
One should note that this works because bool
is an immutable type. If you had a mutable type, let's say X
, you would have to use a comprehension for the inner list, too:
l1 = [[X() for _ in range(n)] for _ in range(m)]
Related Topics
Understanding Ddply Error Message - Argument "By" Is Missing, with No Default
Generate Random Integers Between Two Values with a Given Probability Using R
Load a Dataset into R with Data() Using a Variable Instead of the Dataset Name
Applying Rolling Mean by Group in R
Ggplot2 One Line Per Each Row Dataframe
Cannot Export Data to a File in R (Write.Csv)
Substitute a for B and B for a in a String
Positioning Shiny Widgets Beside Their Headers
Contingency Table Based on Third Variable (Numeric)
Change All Columns from Factor to Numeric in R
Order of Dates Is Not Chronological in Ggplot2
Tukeys Post-Hoc on Ggplot Boxplot
How to Create Group Indices for Nested Groups in R
Quantmod Omitting Tickers in Getsymbols
In R, How to Find the Optimal Variable to Maximize or Minimize Correlation Between Several Datasets