I have two lists:
lst = ['Go','Go','Go','Go','Dont Go!','Go','Go','Go','Dont Go!','Go']
tls = ['G', 'Go', 'Go1', 'Go2', 'Go3']
I need to check for each element in tls if it exists in lst then to output that element, otherwise to output NaN.
I need output to be list like:
['Go', 'Go', 'Go', 'Go', nan, 'Go', 'Go', 'Go', nan, 'Go']
I managed to achieve this by using nested for loops:
ml = []
for t in tls:
for l in lst:
if t in lst:
if t !=l:
ml.append(np.nan)
else:
ml.append(t)
else:
pass
Is it possible to add else clause in this list comprehension in order to achieve the same result?
[t for t in tls for l in lst if t ==l]
The output for this list comprehension:
['Go', 'Go', 'Go', 'Go', 'Go', 'Go', 'Go', 'Go']
Expected output:
['Go', 'Go', 'Go', 'Go', nan, 'Go', 'Go', 'Go', nan, 'Go']
Thank You.
Here's how you could do so using a list comprehension. For a better performance you could take a set of tls
reducing in this way the complexity of checking for membership to O(1)
:
lst = ['Go','Go','Go','Go','Dont Go!','Go','Go','Go','Dont Go!','Go']
tls = set(['G', 'Go', 'Go1', 'Go2', 'Go3'])
[i if i in tls else float('nan') for i in lst]
#['Go', 'Go', 'Go', 'Go', nan, 'Go', 'Go', 'Go', nan, 'Go']
If I understand correctly, you're trying to check for each element in lst
whether that element matches with any element in the list tls
. Then try this :
[t if t in tls else np.nan for t in lst]
Output :
['Go', 'Go', 'Go', 'Go', nan, 'Go', 'Go', 'Go', nan, 'Go']
我不确定我是否正确地理解了您的任务,但是可以简单地实现所需的结果
[t if t in tls else np.nan for t in lst]
Python math
module also introduce math.nan
from Python 3.5 .
A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').
Try this,
>>> from math import nan
>>>
>>> lst = ['Go','Go','Go','Go','Dont Go!','Go','Go','Go','Dont Go!','Go']
>>> tls = ['G', 'Go', 'Go1', 'Go2', 'Go3']
>>> [i if i in tls else nan for i in lst]
['Go', 'Go', 'Go', 'Go', nan, 'Go', 'Go', 'Go', nan, 'Go']
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.