Python - 由列表中的最大邻居替换
给定一个列表,任务是编写一个Python程序来替换前一个和下一个元素之间的最大邻居。
Input : test_list = [5, 4, 2, 5, 8, 2, 1, 9],
Output : [5, 5, 5, 8, 8, 8, 9, 9]
Explanation : 4 is having 5 and 2 as neighbours, replaced by 5 as greater than 2.
Input : test_list = [5, 4, 2, 5],
Output : [5, 5, 5, 5]
Explanation : 4 is having 5 and 2 as neighbours, replaced by 5 as greater than 2.
方法一:使用循环+链条件语句
在这里,我们使用循环遍历列表中的所有元素,并使用条件检查邻居是否有更大的元素,然后被替换。
Python3
# Python3 code to demonstrate working of
# Replacing by Greatest Neighbour
# Using loop + chain conditional statements
# initializing list
test_list = [5, 4, 2, 5, 8, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
for idx in range(1, len(test_list) - 1):
# replacing by greater Neighbour
test_list[idx] = test_list[idx - 1] \
if test_list[idx - 1] > test_list[idx + 1] \
else test_list[idx + 1]
# printing result
print("The elements after replacing : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Replacing by Greatest Neighbour
# Using max() + loop
# initializing list
test_list = [5, 4, 2, 5, 8, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
for idx in range(1, len(test_list) - 1):
# using max() to get maximum of Neighbours
test_list[idx] = max(test_list[idx - 1], test_list[idx + 1])
# printing result
print("The elements after replacing : " + str(test_list))
输出:
The original list is : [5, 4, 2, 5, 8, 2, 1, 9]
The elements after replacing : [5, 5, 5, 8, 8, 8, 9, 9]
方法 2:使用 max() + 循环。
在这里,我们使用 max() 获得相邻元素中的最大元素。循环用于遍历元素。
蟒蛇3
# Python3 code to demonstrate working of
# Replacing by Greatest Neighbour
# Using max() + loop
# initializing list
test_list = [5, 4, 2, 5, 8, 2, 1, 9]
# printing original list
print("The original list is : " + str(test_list))
for idx in range(1, len(test_list) - 1):
# using max() to get maximum of Neighbours
test_list[idx] = max(test_list[idx - 1], test_list[idx + 1])
# printing result
print("The elements after replacing : " + str(test_list))
输出:
The original list is : [5, 4, 2, 5, 8, 2, 1, 9]
The elements after replacing : [5, 5, 5, 8, 8, 8, 9, 9]