我试图找到一种方法来对齐两个对象列表(按其值排序),通过比较它们的值,在两个列表中都对齐的对象上执行一个操作,如果没有对齐则执行另一个操作。例如,使用姓名和年龄对儿童进行对齐。
为了简单起见,可以尝试只使用两个已排序的整数值列表:
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 |
+----+----+----+----+----+----+----+----+----+
要对齐的值执行操作(例如将其附加到列表1中):
list1 = [2,3,6,7]
对于不对齐的值进行操作(例如将其附加到列表2):
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]
我尝试了许多其他方法,但都没有成功。
*编辑:同一列表中没有重复的值。
6
被对齐。您需要更好地定义您所说的“对齐”,也许您的意思是“存在于两个列表中”? - bagrat