比较jython中两个列表的元素

Comparing elements of two lists in jython

我对编码非常陌生,不知道如何在 jython 中有效地比较两个 lists/arrays 中的元素。我有一个长度为 5 的列表和另一个长度为 0 到无穷大的列表。元素没有任何顺序。我想找出两个列表的每个元素之间的区别。因此,如果 list1 = [30, 20, 50, 66, 2] 和 list2 = [6, 50, 90],我应该有 15 个输出 (len(list1)*len(list2))。我知道如何逐一比较每个元素,但我需要一种有效的方法来一次比较所有元素。我想我需要某种迭代器函数,但不知道如何实现它。

This tutorial 控制流程可能会有帮助。

list1 = [30, 20, 50, 66, 2]
list2 = [6, 50, 90]

result = []

for item1 in list1:
    for item2 in list2:
        result.append( item1 - item2 )

print result
#[24, -20, -60, 14, -30, -70, 44, 0, -40, 60, 16, -24, -4, -48, -88]

我想应该这样做:

list_a=[30,20,50,66,2]
list_b=[6,50,90]

for i in list_a:
    for j in list_b:
        #compare here, i am assuming a differnce is the comparision you want to do
        print i-j

我发现列表理解更容易阅读:

from pprint import pprint
list1 = [30, 20, 50, 66, 2]
list2 = [6, 50, 90]

result = [[ one * two for one in list1] for two in list2]
pprint(result)

此处的另一个选项 list comprehensions:

一一比较

print [x==y for x in list2 for y in list1 ]

输出:

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

并打印匹配:

print [ x for x in list2 for y in list1 if x==y ]

输出:

[50]