# Extracting List Values from Python List

Asked 5 months ago, Updated 5 months ago, 10 views

I'm a beginner, so please teach me.

I'd like to extract a value from the list of a that matches the list of b.

`````` a = ['0', '1'', '2', '3', '4', '5', '6', '7', '8', '9']
b = ['0']
if bin a:
print("OK")
else:
print ("NG")
``````

As a result

``````NG
``````

and
It will be displayed.

python

2022-09-30 11:22

From the question, if the list of variables `b` is in the list of `a`, `OK` appears.
`print([i for i in if i in a])` only matches the value.

`````` a = ['0', '1'', '2', '3', '4', '5', '6', '7', '8', '9']
b = ['0']
if [i for i in if i in a ]:
print("OK")
else:
print ("NG")
``````

2022-09-30 11:22

If you want to know if `b` elements are also included in `a`, convert `a` and `b` into a set to see if the former includes the latter as a subset.

`````` a = ['0', '1'', '2', '3', '4', '5', '6', '7', '8', '9']
b = ['0']
if set(b)<=set(a):
print("OK")
else:
print ("NG")
``````

If there are duplicate elements, this method is not available.Alternatively, you may want to count the elements using `Counter`.

`````` from collections import Counter

a = ['0', '1'', '2', '4', '5', '6', '7', '8', '9']
b = ['0']

counter_a = Counter(a)
counter_b = Counter(b)

# For each element of `b`, is the element contained in `a` and is the number of element contained in `a` greater than that contained in `b`?
if all(map(lambdak:kin counter_a and counter_a[k]>=counter_b[k], counter_b)):
print('OK')
else:
print('NG')
``````

2022-09-30 11:22

They want to extract matching values, so I think it would be better to use the set operation.This program converts variables a and b into set sets, respectively, and
Using the & operator to find the logical product, we are extracting a common element of zero.

`````` a = ['0', '1'', '2', '3', '4', '5', '6', '7', '8', '9']
b = ['0']

set_a = set(a)
set_b = set(b)

# logical product commonality extraction
set_a&set_b
# >>{'0'}
``````

In order to deepen my understanding, I expressed it in the image.
Also, I think you should read the reference URL for detailed explanations.

2022-09-30 11:22

"Since your question was ""`a` element included in `b`, there is also a way to use the ""filter"" function to return the list."
(`print('OK')`, `print('NG')` may not be the same in the sense...)

`````` a = ['0', '1'', '2', '3', '4', '5', '6', '7', '8', '9']
b = ['0']
a_in_b=filter(lambdaa_elem:a_elemin b,a)
print(a_in_b)#output: ['0']
``````

2022-09-30 11:22

## If you have any answers or tips

Popular Tags
python x 4628
android x 1593
java x 1493
javascript x 1425
c x 924
c++ x 877
ruby-on-rails x 696
php x 692
python3 x 683
html x 656