Replace the third element of all sublists with another list - python

I have a list of lists and I want to replace/update the third element of all the sublists with a new list.
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
Desired output:
lst_new = [['a','b', 2, 3],['d','e', 3, 9],['g','h', 4, 'j']]

Try this:
lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2, 3, 4]
for x,y in zip(lst1,lst2): #loops over both lst1 and lst2
x[2] = y
output:
[['a', 'b', 2, 3], ['d', 'e', 3, 9], ['g', 'h', 4, 'j']]

Can you use numpy? As simple as:
arr1 = np.array(lst1)
arr1[:, 2] = lst2
Output:
array([['a', 'b', '2', '3'],
['d', 'e', '3', '9'],
['g', 'h', '4', 'j']], dtype='<U1')

lst1 = [['a','b','c', 3],['d','e','f', 9],['g','h','i', 'j']]
lst2 = [2,3,4]
#We make a copy so that this 'lst_new' variable does not point to lst1
lst_new = lst1.copy()
for num, lst in zip(lst2, lst_new):
lst[2] = num
#At this point, your lst_new will be changed

lst1 = [['a', 'b', 'c', 3], ['d', 'e', 'f', 9], ['g', 'h', 'i', 'j']]
lst2 = [2, 3, 4]
for x in range(0, len(lst2)):
lst1[x][2] = lst2[x]
print(lst1)

Just for the fun of having another option:
map(lambda e, subls: [*subls[:2], e, *subls[3:]], lst2, lst1))
It makes use of map, lambda and the unpacking operator *.

Related

Cleaner way to Pop item in list of list

I have a list of lists:
a = [[1,2,'a','b'],[3,4,'c','d'],[5,6,'e','f']]
and I want the result:
[[1,2],[3,4],[5,6]]
and
[['a','b'],['c','d'],['e','f']]
I can do it with a loop and pop but am wondering if there's a better way using slicing or a cleaner method:
d = []
for i in a:
b = i.pop()
c = i.pop()
d.append([c,b])
In: a
Out: [[1, 2], [3, 4], [5, 6]]
In: d
Out: [['a', 'b'], ['c', 'd'], ['e', 'f']]
Unfortunately, there is no way other than iterating over the list of lists.
x,y = [i[:2] for i in a], [i[2:] for i in a]
print(x)
print(y)
[[1, 2], [3, 4], [5, 6]]
[['a', 'b'], ['c', 'd'], ['e', 'f']]
If you are open to using numpy then -
import numpy as np
x,y = np.array(a)[:,:2], np.array(a)[:,2:]
print(x)
print(y)
[['1' '2']
['3' '4']
['5' '6']]
[['a' 'b']
['c' 'd']
['e' 'f']]
You can do it just with a list comprehension:
a = [[1,2,'a','b'],[3,4,'c','d'],[5,6,'e','f']]
first_part = [x[:2] for x in a]
second_part = [x[2:] for x in a]

Adding elements from a list in a nested list - Python

I am using Python 3.6 and Django 1.11. I have a nested list -
nestedList = [[a, b, c], [d, e, f], [g, h, i]]
and another list -
newList = [1,2,3]
I need to club these and want a final list -
finalList = [[a, b, c, 1], [d, e, f, 2], [g, h, i, 3]]
Please let me know how this can be done.
just zip both lists together and create a new sublist:
nestedlist = [[1,2,3],[4,5,6],[7,8,9]]
newlist = [10,11,12]
result = [a+[x] for a,x in zip(nestedlist,newlist)]
print(result)
result:
[[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]]
You can try:
>>> nestedList = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> newList = [1,2,3]
>>>
>>> for num in range(len(newList)):
nestedList[num].append(newList[num])
>>> print nestedList
[['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]
For education purpose, a solution with recursion. Do not use in productive code.
nestedList = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
newList = [1,2,3]
def appendto(L1, L2):
if L1 == []:
return []
else:
return [L1[0] + [L2[0]]] + appendto(L1[1:], L2[1:])
print(appendto(nestedList, newList))
# -> [['a', 'b', 'c', 1], ['d', 'e', 'f', 2], ['g', 'h', 'i', 3]]

python: combine lists of lists for SQLITE table

I need to combine 3 lists into one list so that I can insert it smoothly into sqlite table.
list1= [[a1,b1,c1],[a2,b2,c2]]
list2= [[d1,e1,f1],[d2,e2,f2]]
Output should look like:
combined_list = [[a1,b1,c1,d1,e1,f1],[a2,b2,c2,d2,e2,f2]]
I tried sum list1 + list2 but both didn't work as this output.
You can try this:
from operator import add
a=[[1, 2, 3], [4, 5, 6]]
b=[['a', 'b', 'c'], ['d', 'e', 'f']]
print a + b
print map(add, a, b)
Output:
[[1, 2, 3], [4, 5, 6], ['a', 'b', 'c'], ['d', 'e', 'f']]
[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f']]
Edit:
To add more than two arrays:
u=[[]]*lists[0].__len__()
for x in lists:
u=map(add, u, x)

Returning indexes of intersected lists with Python

I have two lists:
1. ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
2. ['c', 'd']
and I'd like to get indexes of the intersection a, b:
3. [[2, 3], [5, 6]]
How would you do that with Python?
Also these inputs:
1. ['263', '9', '470', '370', '576', '770', '800', '203', '62', '370', '576', '370', '25', '770', '484', '61', '914', '301', '550', '770', '484', '1276', '108']
2. ['62', '370', '576']
should give:
3. [[8, 9, 10]]
One way would be:
>>> l1 = ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
>>> l2 = ['c', 'd']
>>> [range(i,i+len(l2)) for i in xrange(len(l1)-len(l2)+1) if l2 == l1[i:i+len(l2)]]
[[2, 3], [5, 6]]
>>>
For your given example this will work
>>> x = ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'f']
>>> y = ['c', 'd']
>>> z = [[i for i, xi in enumerate(x) if xi == yi] for yi in y]
>>> z
[[2, 5], [3, 6]]
>>> zip(*z)
[(2, 3), (5, 6)]
It makes uses of the enumerate function to get the indices of x along with the values and then transposes the result using zip(*z). You can convert from tuples to lists afterward.
Edit: transposed result.
Maybe a little too much code, but it works.
def indexes(list, element):
c = 0
output = []
for e in list:
if e == element:
output.append(c)
c += 1
return output
a = ['a', 'b', 'c', 'd', 'a']
b = ['a', 'd']
output = []
for el in b:
output.append(indexes(a, el))
print(output)

Unpack a nested list

My question is simple.
There are two lists.
The first is a list of integers:
a = [1, 2, 3]
The other is a list of lists:
b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
How could I get the result below:
result = [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]
Thanks.
>>> a = [1, 2, 3]
>>> b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> [[aa] + bb for aa, bb in zip(a, b)]
[[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]
In Python3
>>> a = [1, 2, 3]
>>> b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> [aa+bb for *aa, bb in zip(a,b)]
[[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']]
Another way to do this would be:
index = 0
l = b
for i in a:
l[index].append(i)
index += 1
The following Python code will unpack each list and assemble it in the form you indicated.
[[a[i]] + b[i] for i in range(min(len(a),len(b)))]
Using Python's enumerate function you can loop over a list with an index. Using x.extend(y) will prepend the values in list x to list y.
a = [1, 2, 3]
b = [['a', 'b'], ['c', 'd'], ['e', 'f']]
result = []
for index, value in enumerate(a):
aa = [value]
aa.extend(b[index])
result.append(aa)

Categories