Python: Compare two lists side by side - python

How do I compare two lists side by side and where the value in List 1 doesn't match the value in List 2, will output that number from List 1? For example:
List1 = [2, 3, 4, 10, 8, 24]
List2 = [2, 9, 4, 23, 8, 24]
Output: [3, 10]

Use List comprehension with zip.
final_lst = [x for x, y in zip(list1, list2) if x!=y]
print(final_lst)

Best solution is to do with zip.
List1 = [2, 3, 4, 10, 8, 24]
List2 = [2, 9, 4, 23, 8, 24]
List2=[x for x, y in zip(List1, List2) if x!=y]
However, a traditional solution
List1 = [2, 3, 4, 10, 8, 24]
List2 = [2, 9, 4, 23, 8, 24]
List3=[]
for j,k in enumerate (List1):
if List1[j]!=List2[j]:
List3.append(k)

Since several people have already suggested a list comprehension, here is a solution without list comprehension, using map and filter:
output = list(map(lambda pair: pair[0], filter(lambda pair: pair[0] != pair[1], zip(lst1, lst2))))
# [3, 10]

Related

How to merge two lists into a new list sequantially? [duplicate]

This question already has answers here:
Interleave multiple lists of the same length in Python [duplicate]
(11 answers)
Closed 3 years ago.
I'm working with lists in Python 3.x.
I want to merge two lists:
list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]
Expected output like this:
list3 = [1, 7, 2, 8, 3, 9, 4, 19]
I am not allowed to use any advanced data structures and need to write in a pythonic way.
Simply we can use list comprehension like this:
list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]
list3 = [v for v1_v2 in zip(list1, list2) for v in v1_v2]
assert list3 == [1, 7, 2, 8, 3, 9, 4, 19]
For example:
from itertools import chain
list(chain(*zip(v1, v2)))
zip() the two lists together then flatten with itertools.chain.from_iterable():
>>> from itertools import chain
>>> list1 = [1,2,3,4]
>>> list2 = [7,8,9,19]
>>> list(chain.from_iterable(zip(list1, list2)))
[1, 7, 2, 8, 3, 9, 4, 19]
You can simply use reduce from functools over a sum of the two lists using zip
from functools import reduce
from operator import add
list1 = [1,2,3,4]
list2 = [7,8,9,19]
x = list(reduce(add, zip(list1, list2)))
x
[1, 7, 2, 8, 3, 9, 4, 19]
Try the below code:
list1 = [1, 2, 3, 4]
list2 = [7, 8, 9, 19]
new_list = []
for i in range(len(list1)):
new_list.extend([list1[i], list2[i]])
print(new_list)
Output:
[1, 7, 2, 8, 3, 9, 4, 19]

How to add elements of python lists in a dictionary

Below is list of arrays:
{'array_1': [1, 2, 3, 4], 'array_2': [3, 4, 5, 6], 'array_3': [7, 8, 9, 0]}
Code for array input:
def main():
a = int(input("Enter the number of array's: "))
size = int(input('Each array size: '))
arrays = dict()
for i in range(1, a + 1):
arrays['array_' + str(i)] = list(
map(lambda j: int(input('value: ')), [j for j in range(size)]))
print(arrays)
I want to add 'array_1' with array_2
Just for clarification, you have a dictionary of lists, not a list of arrays. I think this is what you're looking for
list_dict = {'array_1': [1, 2, 3, 4], 'array_2': [3, 4, 5, 6], 'array_3': [7, 8, 9, 0]}
[sum(items) for items in zip(list_dict['array_1'], list_dict['array_2'])]
this results in the list [4, 6, 8, 10] - I'm assuming that's what you mean by add array_1 and array_2
If by add you mean concatenate do this:
new_list = array['array_1'] + array['array_2']
else if you mean addition of individual values you can do:
from operator import add
new_array = list(map(add,array['array_1'],array['array_2']))
If you want to sum element wise then
d= {'array_1': [1, 2, 3, 4], 'array_2': [3, 4, 5, 6], 'array_3': [7, 8, 9, 0]}
[sum(x) for x in zip(*d.values())] # will add elements from all the lists
Output:
[11, 14, 17, 10]
going along the same lines if you just want to add lists corresponding to some keys then you can filter the keys to create a new dict and use it in a same way
[sum(x) for x in zip(*{key:value for key,value in d.items() if key in ['array_1','array_2']}.values())]
Output
[4, 6, 8, 10]

How to convert a two dimensional list into a list of each row

A=[[1,3,5,7],[2,5,8,12,16],[4,7,8,12]]
I would like the result to be
[1,3,5,7][2,5,8,12,16][4,7,8,12]
you can unpack your list A like this:
A = [[1,3,5,7],[2,5,8,12,16],[4,7,8,12]]
list1, list2, list3 = A
print(list1, list2, list3)
output:
[1, 3, 5, 7] [2, 5, 8, 12, 16] [4, 7, 8, 12]
in this case, you have to be sure that A has always 3 lists inside

List of lists python: combine list elements that are the same size

I have a list of lists in python:
[[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]
I would like to combine the sublists into a single sublist if they hold the same number of elements:
[[1,2,17],[3,4,5,6],[7,8,9,10,11,12,13,14,15,16]]
Is there a simple way of doing this?
Use groupby and chain from itertools
Ex:
from itertools import groupby, chain
lst = [[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]
result = [list(chain.from_iterable(v)) for k, v in groupby(sorted(lst, key=lambda h: len(h)), lambda x: len(x))]
print(result)
Output:
[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
sorted(lst, key=lambda h: len(h)) to sort your list by len
then use groupby to group your list by len of list
A "simpler" approach without itertools:
dictByLength = {}
for i in mylist:
dictByLength[len(i)] = dictByLength.get(len(i), []) + i
print(list(dictByLength.values()))
output:
[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]
Here is my approach (without using itertools):
l = [[1],[2],[3,4],[5,6],[7,8,9,10,11],[12,13,14,15,16],[17]]
# create one sublist for each possible length
m = [[] for size in range(len(max(l, key=len)))]
# append to each size-sublist, the appropriate sublist
for sub_l in l:
size = len(sub_l)
m[size - 1] += sub_l
# remove empty sub lists
m = [sub_m for sub_m in m if sub_m]
print(m)
[[1, 2, 17], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]]

Sum lists of variable lengths element-wise

If I have a list of lists, and each nested list contains numbers, how can I add all of these lists element-wise into a single array?
i.e.
listOne = [1, 2, 3]
listTwo = [4, 5, 6]
listThree = [7, 8, 9, 10]
allLists = [listOne, listTwo, listThree]
total = add(allLists)
print total
output should be [12, 15, 18, 10]
Use izip_longest to remap rows/columns (like zip but to the longest element rather than shortest), filling shorter items 0
from itertools import izip_longest
total = [sum(x) for x in izip_longest(*allLists, fillvalue=0)]
Outputs:
[12, 15, 18, 10]
Also for your edification, the intermediate output of the zip_longest is:
[(1, 4, 7), (2, 5, 8), (3, 6, 9), (0, 0, 10)]
This is also a nice opportunity to practice list comprehensions ;)
maxlen = max(len(lst) for lst in allLists) # find length of longest list
sumlist = [sum([lst[i] if i<len(lst) else 0 for lst in allLists]) for i in range(maxlen)]
gives sumlist
[12, 15, 18, 10]

Categories

Resources