Mistake in list comprehension - python-3.x

Problem Solved!
I have two python lists of integers that are randomly generated. I want to find the numbers that are common between the lists.
Using list comprehension, I've come up with this:
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
However, this returns an empty list. I have a working program using loops that works perfectly:
for a in list_one:
for b in list_two:
if a == b and a not in new_list:
new_list.append(a)
What mistakes have I made converting it to a list comprehension?

This is a simple approach with sets,
list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]
new_list = list(set(list_1) & set(list_2))
print(new_list)
It uses the set intersection has a number of benefits compared to a list comprehension:
The input lists do not need to be sorted (though you can sort them by using sorted() function.
The input lists can have different lengths.
Presence of duplicates is taken care of automatically (sets don't admit those).

I do not think list comprehension is required for intersection of 2 lists.
Anyways you can modify your code to-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
print(new_list)
you can also do-
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one if a in list_two and a not in new_list]
print(new_list)
You can convert it into set and use set1.intersection(set2).
list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = list(set(list_one).intersection(set(list_two)))
print(new_list)

You can't reference the same list inside of a list comprehension.
Thanks #Keith from the comments of the OP for pointing it out.

Related

How to get unique values in nested list along single column?

I need to extract only unique sublists based on first element from a nested list. For e.g.
in = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = [['a','b'], ['e','f'], ['g','h']]
My method is two break list into two lists and check for elements individually.
lis = [['a','b'], ['a','d'], ['e','f'], ['g','h']]
lisa = []
lisb = []
for i in lis:
if i[0] not in lisa:
lisa.append(i[0])
lisb.append(i[1])
out = []
for i in range(len(lisa)):
temp = [lisa[i],lisb[i]]
out.append(temp)
This is an expensive operation when dealing with list with 10,00,000+ sublists. Is there a better method?
Use memory-efficient generator function with an auziliary set object to filter items on the first unique subelement (take first unique):
def gen_take_first(s):
seen = set()
for sub_l in s:
if sub_l[0] not in seen:
seen.add(sub_l[0])
yield sub_l
inp = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = list(gen_take_first(inp))
print(out)
[['a', 'b'], ['e', 'f'], ['g', 'h']]

use list comprehensions to eliminate strings in list that include substrings in another list

I have two lists:
list_1 = ['https:/zh-cn.fb.com/siml15', 'https:/fb.com/siml29','https:/en-gb.fb.com/siml29','https:/fb.com/siml4529','https:/pt-br.fb.com/siml29']
list_2 = ['zh-cn','en-gb','es-la','fr-fr','ar-ar','pt-br','ko-kr','it-it','de-de','hi-in','ja-jp']
I need to remove items in list_1 that includes substrings in list_2
The wanted output:
['https:/fb.com/siml29','https:/fb.com/siml4529']
Is there a way to use list comprehensions twice?
[x for x in list_1 if y for y in list_2 not in x]
You can use inner comprehension and all function for this:
list_1 = ['https:/zh-cn.fb.com/siml15', 'https:/fb.com/siml29', 'https:/en-gb.fb.com/siml29', 'https:/fb.com/siml4529', 'https:/pt-br.fb.com/siml29']
list_2 = ['zh-cn', 'en-gb', 'es-la', 'fr-fr', 'ar-ar', 'pt-br', 'ko-kr', 'it-it', 'de-de', 'hi-in', 'ja-jp']
result = [x for x in list_1 if all(y not in x for y in list_2)]
print(result)
['https:/fb.com/siml29', 'https:/fb.com/siml4529']

In the for loop why does it not square the last number in the list?

I am trying to create a code that will add up a list of numbers which have been squared. I am pretty new to python, so I was wondering if someone could explain why the list1 produced does not include the last number squared. The list2 always seems to start with 0. Can someone explain why?
import math
list2=[]
values=input("Please enter your vector coordinates")
list1=values.split()
print(list1)
for i in range(len(list1)):
value=i**2
list2.append(value)
print(list2)
i is the index, not the value, you can use either indexing:
for i in range(len(list1)):
value = list1[i]**2
list2.append(value)
Or simply use for i in list1:
for i in list1:
value = i**2
list2.append(value)
Even simpler with a list comprehension:
list2 = [i ** 2 for i in list1]
list2 always starts with a 0 because the first value of i is always 0. When you call range(len(list1)), you are asking for all the numbers in the sequence 0, 1, 2, 3, ..., N; where N is the number of elements in list1. Note that these are not the specific elements in list1.
Assuming that list1 has numbers in it, creating list2 with the squares of the corresponding numbers can be achieved in this way:
list2 = []
for num in list1:
v = num**2
list2.append(v)
There's another error in your code: list1 does not contain numbers as desired. In fact, it contains a bunch of strings (each of which looks like a number) but these are strs, not ints. This is because input returns a string, not ints. Continuing from there, values.split() gives you a list of strings, not a list of numbers. So you'll have to cast them to ints yourself:
list1 = [int(v) for v in values.split()]
Here's how I'd write this code:
list2 = []
values = input("Please enter your vector coordinates")
list1 = list(map(int, values.split()))
print(list1)
for num in list1:
list2.append(num**2)
print(list2)

Python: How to find the average on each array in the list?

Lets say I have a list with three arrays as following:
[(1,2,0),(2,9,6),(2,3,6)]
Is it possible I get the average by diving each "slot" of the arrays in the list.
For example:
(1+2+2)/3, (2+0+9)/3, (0+6+6)/3
and make it become new arraylist with only 3 integers.
You can use zip to associate all of the elements in each of the interior tuples by index
tups = [(1,2,0),(2,9,6),(2,3,6)]
print([sum(x)/len(x) for x in zip(*tups)])
# [1.6666666666666667, 4.666666666666667, 4.0]
You can also do something like sum(x)//len(x) or round(sum(x)/len(x)) inside the list comprehension to get an integer.
Here are couple of ways you can do it.
data = [(1,2,0),(2,9,6),(2,3,6)]
avg_array = []
for tu in data:
avg_array.append(sum(tu)/len(tu))
print(avg_array)
using list comprehension
data = [(1,2,0),(2,9,6),(2,3,6)]
comp = [ sum(i)/len(i) for i in data]
print(comp)
Can be achieved by doing something like this.
Create an empty array. Loop through your current array and use the sum and len functions to calculate averages. Then append the average to your new array.
array = [(1,2,0),(2,9,6),(2,3,6)]
arraynew = []
for i in range(0,len(array)):
arraynew.append(sum(array[i]) / len(array[i]))
print arraynew
As you were told in the comments with sum and len it's pretty easy.
But in python I would do something like this, assuming you want to maintain decimal precision:
list = [(1, 2, 0), (2, 9, 6), (2, 3, 6)]
res = map(lambda l: round(float(sum(l)) / len(l), 2), list)
Output:
[1.0, 5.67, 3.67]
But as you said you wanted 3 ints in your question, would be like this:
res = map(lambda l: sum(l) / len(l), list)
Output:
[1, 5, 3]
Edit:
To sum the same index of each tuple, the most elegant method is the solution provided by #PatrickHaugh.
On the other hand, if you are not fond of list comprehensions and some built in functions as zip is, here's a little longer and less elegant version using a for loop:
arr = []
for i in range(0, len(list)):
arr.append(sum(l[i] for l in list) / len(list))
print(arr)
Output:
[1, 4, 4]

How to concatenate 2 list strings using list comprehension

I have 2 lists as below:
list1 = ['A','B']
list2 = ['C','D']
The required output should be [['AC','BC'], ['AD','BD']] using List comprehension.
Using two for loops as a list comprehension
list1= ['A','B']
list2= ['C','D']
b=[[l+p for l in list1] for p in list2]
print(b)

Resources