[英]Python Nested Loops And Else Clause in List Comprehension
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.我需要检查 tls 中的每个元素是否存在于 lst 中,然后输出该元素,否则输出 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:我设法通过使用嵌套的 for 循环来实现这一点:
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?是否可以在此列表理解中添加 else 子句以获得相同的结果?
[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)
: 为了获得更好的性能,您可以采取一组tls
减少以这种方式检查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
. 如果我理解正确,那么您正在尝试检查lst
每个元素,该元素是否与列表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 . Python math
模块还引入了Python 3.5中的 math.nan
。
A floating-point “not a number” (NaN) value. 浮点“非数字”(NaN)值。 Equivalent to the output of float('nan'). 等效于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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.