gpt4 book ai didi

python - 对齐两个列表并对对齐和未对齐的对象执行操作

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:00 27 4
gpt4 key购买 nike

我试图找到一种方法来对齐两个对象列表(按其值排序)并通过比较它的值,如果对象在两个列表中对齐则执行一个操作,否则执行另一个操作。例如 kids 有他的名字和年龄,并使用年龄值来对齐它们。

为使示例简单,请尝试仅使用两个排序的整数值列表:

a = (1,2,3,6,7,11,13)
b = (2,3,4,6,7,9)

我想像这样对齐它们:

+----+----+----+----+----+----+----+----+----+
| 01 | 02 | 03 | xx | 06 | 07 | xx | 11 | 13 |
+----+ +----+ +----+----+----+
| xx | 02 | 03 | 04 | 06 | 07 | 09 | xx | xx |
+----+----+----+----+----+----+----+----+----+

对对齐值执行操作(例如将其附加到 list1):

list1 = [2,3,6,7]

并对未对齐的值执行操作(例如将其附加到 list2):

list2 = [1,4,9,11,13]

或者只是打印是否对齐:

1 = miss-aligned
2 = aligned
3 = aligned
4 = miss-aligned
6 = aligned
7 = aligned
9 = miss-aligned
11 = miss-aligned
13 = miss-aligned

我尝试过这种方式但是......

a = (1,2,3,6,7,11,13)
b = (2,3,4,6,7,9)
list1 = []
list2 = []

# find sames and list a different value
for x in a:
for y in b:
if x == y:
list1.append(x)
print(x," = aligned")
break
if y == b[-1]:
print(x," = miss-aligned")
list2.append(x)

# find list b different value
for y in b:
for x in a:
if x == y:
break
if x == a[-1]:
print(y," = miss-aligned")
list2.append(y)

print('Same:',list1)
print('Different:',list2)

...我得到了这个不想要的输出(没有按顺序执行 4 和 9 的操作):

1  = miss-aligned
2 = aligned
3 = aligned
6 = aligned
7 = aligned
11 = miss-aligned
13 = miss-aligned
4 = miss-aligned
9 = miss-aligned
Same: [2, 3, 6, 7]
Different: [1, 11, 13, 4, 9]

我尝试了很多其他方法都没有成功。

*编辑:同一列表中没有重复的值

最佳答案

由于列表已排序,您可以执行以下操作:

def same_diff(a, b):
sames = []
diffs = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
sames.append(a[i])
i += 1
j += 1
elif a[i] > b[j]:
diffs.append(b[j])
j += 1
else:
diffs.append(a[i])
i += 1
diffs += a[i:]
diffs += b[j:]
return sames, diffs

a = (1,2,3,6,7,11,13)
b = (2,3,4,6,7,9)

same_diff(a, b)
# ([2, 3, 6, 7], [1, 4, 9, 11, 13])

如果您正在对这些值进行操作而不是附加剩余的值,您可以遍历它们:

def same_diff(a, b):
sames = []
diffs = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
print 'aligned', a[i]
sames.append(a[i])
i += 1
j += 1
elif a[i] > b[j]:
print 'miss-aligned', b[j]
diffs.append(b[j])
j += 1
else:
print 'miss-aligned', a[i]
diffs.append(a[i])
i += 1
while i < len(a):
print 'miss-aligned', a[i]
diffs.append(a[i])
i += 1
while j < len(b):
print 'miss-aligned', b[j]
diffs.append(b[j])
j += 1
return sames, diffs

会导致:

same_diff(a, b)

miss-aligned 1
aligned 2
aligned 3
miss-aligned 4
aligned 6
aligned 7
miss-aligned 9
miss-aligned 11
miss-aligned 13
# ([2, 3, 6, 7], [1, 4, 9, 11, 13])

关于python - 对齐两个列表并对对齐和未对齐的对象执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30350572/

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