【问题标题】:Compare elements of two list比较两个列表的元素
【发布时间】:2020-07-04 22:04:39
【问题描述】:

我得到了两个列表,比如 list1 和 list2。我必须以这样一种方式排列 list1 的元素,即在特定索引处,list1 的元素大于 list2 的元素。我们必须找出 list1 中有多少这样的元素。 例如:

list1=[20,30,50]
list2=[60,40,25]

这里只有元素索引 2 更大,即 50>25,但是如果我们在 list1 中交换 50 和 30 所以,

list1=[20,50,30]
list2=[60,40,25]

然后 50 > 40(在索引 1 处)和 30 > 25(在索引 2 处)。所以我们得到了 2 个元素 50 和 30,它们在各自的索引中都更大。 这是我的方法

def swap(a,b):
    a,b=b,a
    return a,b
n=3
g=list(map(int,input().split()))
o=list(map(int,input().split()))
c=0
for i in range(n):
    if o[i]>g[i]:
        for j in range(i+1,n):
            if g[j]>o[i]:
                g[i],g[j]=swap(g[i],g[j])
                c+=1
                break
    else:
        c+=1
print(c)

但是对于

list1= [3,6,7,5,3,5,6,2,9,1]
list2= [2,7,0,9,3,6,0,6,2,6]

它给出 c=6 但预期输出是 c=7

【问题讨论】:

  • 最终列表的顺序重要吗?
  • 这不是一个 Python 问题,而是一个算法问题。也许建议用伪代码的算法?
  • 20 不大于 60 时,为什么 20 和 60 留在原来的索引位置?
  • @ChrisDoyle 因为 list1 中没有大于 60 的元素
  • 那么您的预期输出是什么?列表 1 中有多少元素大于列表 2 中的元素?

标签: python python-3.x list list-comparison


【解决方案1】:

您必须对这两个列表进行排序,然后遍历它们以找到 list1 的值大于 list2 的下一个值的“匹配项”。这会将具有最小可能差异的值配对,从而最大化配对。

例如:

list1=[20,30,50]
list2=[60,40,25]

iter1 = iter(sorted(list1))  # iterator to run through sorted list1
n1    = next(iter1,None)     # n1 is current number in list1
count = 0                    # count of paired elements (n1>n2)
for n2 in sorted(list2):               # go through sorted list 2
    while n1 is not None and n1 <= n2: # skip over ineligible items of list1
        n1 = next(iter1,None)
    if n1 is None: break               # stop when list 1 is exhausted
    count += 1                         # count 1 pair and move on to next of list2

print(count) # 2

【讨论】:

    【解决方案2】:
    list1= [3,6,7,5,3,5,6,2,9,1]
    list2= [2,7,0,9,3,6,0,6,2,6]
    
    list1 = sorted(list1)
    it = iter(enumerate(list1))
    list2  = sorted(list2)
    c = next(it)
    good = []
    for i, n in enumerate(list2 ):
        try:
            while c[1] < n:
                c = next(it)
            good.append([i, c[0]])
            c = next(it)
        except StopIteration:
            break
    
    for idx1, idx2 in good:
        list1[idx1], list1[idx2] = list1[idx2], list1[idx1]
    
    final_l1_l2 = sum(a > b for a, b in zip(list1, list2))# how many l1 are > l2
    print(final_l1_l2)
    

    输出:

       7
    

    另外,您可以在重新排列后打印 list1 和 list2:

    print(list1)
    print(list2)
    

    输出:

    [1, 2, 3, 3, 5, 6, 6, 7, 9, 5]
    [0, 0, 2, 2, 3, 6, 6, 6, 7, 9]
    

    想法是对两个列表进行排序,然后检查list1 中的哪些元素大于list2 中的元素,如果list1 中的一个元素小于list2 中的当前元素,只需转到list1 中的下一个元素,直到 list1 中没有更多元素

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多