gpt4 book ai didi

python - 比较两个列表的元素

转载 作者:行者123 更新时间:2023-12-04 10:21:20 25 4
gpt4 key购买 nike

我得到了两个列表,比如 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

最佳答案

您必须对两个列表进行排序,然后遍历它们以查找 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

关于python - 比较两个列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com