Python - 列表之间的最大差异
给定两个列表,任务是编写一个Python程序来查找相似索引元素之间的最大差异。
例子:
Input : test_list1 = [3, 4, 2, 1, 7], test_list2 = [6, 2, 1, 9, 1]
Output : 8
Explanation : 9 – 1 = 8 is maximum difference across lists in same index.
Input : test_list1 = [3, 4, 2, 1, 17], test_list2 = [6, 2, 1, 9, 1]
Output : 16
Explanation : 17 – 1 = 16 is maximum difference across lists in same index.
方法 1:使用列表理解+ max()
在这种情况下,使用 abs() 计算差异并使用列表理解完成迭代。 max() 用于获取计算子结果之间的最大差异的任务。
Python3
# Python3 code to demonstrate working of
# Maximum difference across lists
# Using list comprehension + max()
# initializing lists
test_list1 = [3, 4, 2, 1, 7]
test_list2 = [6, 2, 1, 9, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using max() to get maximum of extracted difference
res = max(abs(test_list2[idx] - test_list1[idx])
for idx in range(0, len(test_list1) - 1))
# printing result
print("Maximum difference among lists : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum difference across lists
# Using zip() + max()
# initializing lists
test_list1 = [3, 4, 2, 1, 7]
test_list2 = [6, 2, 1, 9, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using max() to get maximum of extracted difference
# zip() used to bind elements
res = max(abs(ele1 - ele2) for ele1, ele2 in zip(test_list1, test_list2))
# printing result
print("Maximum difference among lists : " + str(res))
输出:
The original list 1 is : [3, 4, 2, 1, 7]
The original list 2 is : [6, 2, 1, 9, 1]
Maximum difference among lists : 8
方法 2:使用zip() + max()
在这种类似索引元素的配对中,使用 zip() 完成。其余所有功能与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# Maximum difference across lists
# Using zip() + max()
# initializing lists
test_list1 = [3, 4, 2, 1, 7]
test_list2 = [6, 2, 1, 9, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using max() to get maximum of extracted difference
# zip() used to bind elements
res = max(abs(ele1 - ele2) for ele1, ele2 in zip(test_list1, test_list2))
# printing result
print("Maximum difference among lists : " + str(res))
输出:
The original list 1 is : [3, 4, 2, 1, 7]
The original list 2 is : [6, 2, 1, 9, 1]
Maximum difference among lists : 8