繁体   English   中英

Python-小于或等于要与两个列表进行比较?

[英]Python - Less than or Equal To Compare with two lists?

Python的新手,所以这可能是一个愚蠢的问题,但是经过一天的研究和执行代码,我仍无法弄清楚这个问题。

我想获取两个整数列表(结果和设置)并以以下格式比较它们:

(Setting# - 0.1) <= Result# <= (Setting# +0.1)

我需要对列表中的所有#执行此操作。

例如,如果Result1=4.6Setting1=4.3 ,我希望它比较4.2 <= 4.6 <= 4.4(这将导致失败,因为它超出了我的公差0.1 。一旦比较,我将希望它继续遍历列表直到完成。

这似乎不起作用,因为我有它。 有任何想法吗?

results = [Result1, Result2, Result3, Result4, Result5, Result6]
settings = [Setting1, Setting2, Setting3, Setting4, Setting5, Setting6]
for n in results and m in settings:
    if (m-.1) <= n <= (m+.1): #compare values with a + or - 0.1 second error tolerance
    print 'ok'
else:
    print 'fail'
print 'Done'

您需要使用zip来串联访问resultssettings

for n, m in zip(results, settings):
    if m - 0.1 <= n <= m + 0.1:
        print 'ok'
    else:
        print 'fail'
print 'Done' 

您需要使用zip()组合两个列表:

for n, m in zip(results, settings):
    if (m-.1) <= n <= (m+.1):
        print 'ok'
    else:
        print 'fail'

zip()创建一个新列表,该列表通过组合每个输入序列中的每个第n个元素而制成:

>>> a = range(5)
>>> b = 'abcde'
>>> zip(a, b)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]

您可以使用all()进行短路测试; all()尽快返回False 我们在这里使用itertools.izip()来避免创建一个可能仅测试前几对的全新列表:

from itertools import izip

if all((m-.1) <= n <= (m+.1) for n, m in izip(results, settings)):
    print 'All are ok'
else:
    print 'At least one failed'

与列表和python几乎一样,可以在一行中完成:

print('ok' if all(setting - 0.1 <= result <= setting + 0.1 
    for setting, result in zip(settings, results)) else 'fail')
Setting = [4,3,5,6]
Result = [3,3.02,5.001,8]

print([ (x - 0.1) <= y <= (x + 0.1) for x,y in zip(Setting, Result)])

然后将结果作为布尔值列表

>>> 
[False, True, True, False]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM