Append two individual lists to list of lists - python

Let's say I have:
a=[1,2,3]
b=[4,5,6]
Now I want to create a list of list from a and b, I would do it like this:
c=[a,b]=[[1,2,3],[4,5,6]]
As a.append(b) would result in: [1,2,3,b]=[1,2,3,[4,5,6]]
Now let's say there exists anew list which I want to append to c:
d=[7,8,9]
I now have to do c.append(d) to get [[1,2,3],[4,5,6],[7,8,9]]
Because
e=[c,d]=[[[1,2,3],[4,5,6]],[7,8,9]]
How can I get a list of list from individual lists without know how my lists are structured?

Try this:
a = [1,2,3]
b = [4,5,6]
c = []
c.append(a)
c.append(b)
This should work, and only takes 2 simple lines.

The two actions you are describing are distinctly different. The first is creating the outer list (a.k.a. c) and the second is appending to it.
To make the process more uniform you can just start off with an outer list and append all the child lists to it.
c = []
a=[1,2,3]
b=[4,5,6]
d=[7,8,9]
c.append(a)
c.append(b)
c.append(d)
c is now
[[[1,2,3],[4,5,6]],[7,8,9]]

A bit roundabout of a way but looks nice, using numpy
a = np.array([[1,2,3]])
b = np.array([[4,5,6]])
c = np.append(a,b,axis=0)
print(c.tolist())
gives you
[[1,2,3],[4,5,6]]
Appending another list in the same way keeps the structure of list of lists, for example
d = np.array([[7,8,9]])
e = np.append(c,d,axis=0)
print(e.tolist())
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Now this is quite roundabout. I would just keep everything in numpy arrays if possible.
EDIT: Figured out how to do this without numpy
Simply state each list as a list of lists to begin with
a = [[1,2,3]]
b = [[4,5,6]]
a.extend(b)
print(a)
[[1,2,3],[4,5,6]]
Furthermore you can do this
d = [[7,8,9]]
a.extend(d)
print(a)
[[1, 2, 3], [4, 5, 6], [4, 5, 6]]

Related

Find lists in list of lists with the most instances from another list

I have a list:
a = [10,9,1,2,3,4]
And a list of lists:
b = [[1,2,3],[6,9,10],[4,5,7,8]]
I want to get:
c = [[1,2,3],[6,9,10]]
Where c is the list of top 2 lists in b with the most instances in a.
These can be large, so performance could be an issue.
Not sure if this makes a differences, but each element is present only once in a and the entirety of b and is an integer.
The heapq module has a nlargest function that will efficiently get you the top n values from a list without sorting the whole thing. Use a set to get the intersection of values in a with each sub list:
from heapq import nlargest
a = [10,9,1,2,3,4]
b = [[1,2,3],[6,9,10],[4,5,7,8]]
aSet = set(a)
c = nlargest(2,b,key=lambda n:len(aSet.intersection(n)))
print(c)
[[1, 2, 3], [6, 9, 10]]

I want to know list parmeters in python function like a[:]

pset = []
def powe(a):
powehelp(a,0)
def powehelp(a, ind):
if len(a) == ind:
pset.append(a)
return
powehelp(a[:], ind+1)
a.pop(ind)
powehelp(a[:],ind)
powe([1,2,3])
print(pset)
This code creates its subset, and in this code I want to know why I can't use powehelp(a, ind+1) instead of powehelp(a[:], ind+1)?
I know that a[:] means get all the values ​​of list a.
When using a, the result is [[], [], [], []].
Your powehelp function uses pop, which means it alters the list it is given.
If you pass a into it, it is a that gets altered, and evidently ends up empty.
a[:] creates a copy of a. If you pass a[:] into powehelp, your original list a is unaffected.
The given a is a list in itself, and so appending a list to a list would make a nested list.
a = [1, 2, 3]
b = []
b.append(a)
b
[[1, 2, 3]]
When you pset.append(a) you insert the list a into the endtail of the list pset so you result is a nested list. If I understand your requirement correctly, you're looking to concatenate your lists, as in:
c = [4, 5, 6]
a + c
[1, 2, 3, 4, 5, 6]

Python nested list comprehension (accessing nested elements) [duplicate]

This question already has answers here:
Explanation of how nested list comprehension works?
(11 answers)
Closed 5 years ago.
I'm having trouble understanding the syntax here.
matrix_a = [[1, 2], [3, 4], [5, 6]]
matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[a for a, b in matrix_a]
output: [1, 3, 5]
[a for b, a in matrix_a]
output: [2, 4, 6]
I understand a little about how list-comprehensions work, but I don't understand the syntax when accessing certain elements within a nested list.
I just can't wrap my head around this syntax. How is this syntax working? What does the comma represent? What does a for a mean? Can you explain whats going on under the hood? And finally how would you do this with matrix_b
If you convert it to a for loop it might be easier to see..?
res = []
for item in matrix_a:
a, b = item # a = item[0]; b = item[1]
res.append(a)
you're basically unpacking the individual items in the list and picking one of them.
I think you have mistaken in writing output here
[a for a, b in matrix_a] returns [1 2 4] which is logical , returning first element of each nested list item
see the screenshot
just understand in this way:
[a for b, a in matrix_a] #as
[a for [a, b] in matrix_a] #or
[a for (a, b) in matrix_a]
#matrix_a has elements as list of length 2 each
#so your list comprehenssion says, give me a output list -- having first element'a' from each element of matrix_a(whose each element represented as [a,b] type, with comma, becomes tuple (a,b)),
# then from [b,a] give me a, that is 2nd element
# and it will fail if you apply same on matrix_b, cause each element of matrix_b is not of type [a,b] i:e of length 2
# you will get "ValueError: too many values to unpack"
Let me know if anything is not clear. Thanks.

Why lists cannot be indexed with a list of indexes?

I am asking this question related to this one:
Access multiple elements of list knowing their index
Basically if you have a list and want to get several elements you cannot just pass a list of indexes.
Example:
a = [-2,1,5,3,8,5,6]
b = [1,2,5] # list of indexes
a[b] #this doesn't work
# expected output: [1,5,5]
To solve this problem several options are proposed in the linked question:
Using list comprehension:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
c = [a[i] for i in b]
Using operator.itemgetter:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print itemgetter(*b)(a)
or using numpy arrays (which DO accept indexing with lists)
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print list(a[b])
My question is: Why normal lists don't accept this? This will not conflict the normal indexing [start:end:step] and will provide another way of accessing list elements without using external libraries.
I don't intend this question to attract opinion based answers but rather to know if there is an specific reason why this feature is not available in Python, or if it will be implemented in a future.
Another way we can get the expected output, and it might can be implemented into python function related with list.
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
def getvalues(original_list, indexes_list):
new_list = []
for i in indexes_list:
new_list.append(original_list[i])
return new_list
result = getvalues(a, b)
print(result)
A simple and easy approach to do it can be done in a list comprehension:
a = [-2,1,5,3,8,5,6]
b = [1,2,5]
multi_index = lambda l1, l2: [l1[i] for i in l2]
>>> print(multi_index(a,b))
[1, 5, 5]

Remove arrays from nested arrays based on first element of each array

I have two nested arrays say
a=[[1,2,3],[2,4,7],[4,2,8],[3,5,7],[6,1,2]]
b=[[1,6,7],[2,4,9],[4,3,5],[3,10,2],[5,3,2],[7,2,1]]
I want to only keep those arrays in b whose first element is not common to the first elements of the arrays in a, so for these two we should get
c=[[5,3,2],[7,2,1]]
Is there a way to do this in python?
You may do like this,
>>> a=[[1,2,3],[2,4,7],[4,2,8],[3,5,7],[6,1,2]]
>>> b=[[1,6,7],[2,4,9],[4,3,5],[3,10,2],[5,3,2],[7,2,1]]
>>> [i for i in b if i[0] not in [j[0] for j in a]]
[[5, 3, 2], [7, 2, 1]]
>>>
or
>>> k = [j[0] for j in a]
>>> [i for i in b if i[0] not in k]
[[5, 3, 2], [7, 2, 1]]
To make this a little faster and efficient using set
Code:
list1 = [[1,2,3], [2,4,7], [4,2,8], [3,5,7], [6,1,2]]
list2 = [[1,6,7], [2,4,9], [4,3,5], [3,10,2], [5,3,2], [7,2,1]]
check_set=set(val[0] for val in list1 )
print [val for val in list2 if val[0] not in check_set]
Output:
[[5, 3, 2], [7, 2, 1]]
Notes:
First we are creating a set to store all the unique first value of list1
The set is used to remove duplicate values at the same time member check in set is almost O(1) i.e.) 0 in set([0,1,2]) is O(1) member checking in list can go to a worst case of O(n)
Finally creating a list by iterating over list2 and checking if the first element is not present in set
This sounds like a homework problem, but I'm going to trust that this isn't one.
You can do this easily in two steps:
Store all first elements from a in a set.
Filter our lists in b whose first elements do not exist in the set.
def remove_common(a, b):
"""remove lists from b whose first element is the first element of a list in a"""
first_elements = set(sublist[0] for sublist in a)
return list(filter(lambda sublist: sublist[0] not in first_elements, b))
With dictionaries to enhance the data structure and garantees a linear complexity, assuming all l[0] are differents :
source,target={l[0]:l for l in a},{l[0]:l for l in b}
[target[key] for key in target.keys()-source.keys()]
You could assign c with a nested list comprehension.
c = [each_b for each_b in b if each_b[0] not in [each_a[0] for each_a in a]]
print(c)
>>> [[5, 3, 2], [7, 2, 1]]

Categories

Resources