As the title states, I would like to know how to use "list comprehension" to shorten this for loop. The loop is functional; however, the details of the assignment given to me states that I should have at least one list comprehension and this was the only for loop in my code. By the way, I am fairly new to python.
z=0
for elements in a
if a[z] in c:
z=z+1
elif a[z] in b:
c.append(a[z])
z=z+1
else:
z=z+1
Also, if there are any general tips to shorten this, that would be much appreciated.
I assume what you want is to take elements from a
and place them in c
if those elements are present in b
. Also you want to make sure that only one such element exits in c
, meaning c
is a set.
You can do that as
>>> a = [1, 3, 5, 7, 3]
>>> b = [3, 5]
>>> set([ i for i in a if i in b ])
set([3, 5])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.