用列表中的第 j 个元素交换第 i 个元素的Python程序
给定一个列表,任务是将Python程序写入给定的元素列表,切换列表中的每个 i 和 j 元素。
例子:
Input : test_list = [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4], i, j = 4, 8
Output : [8, 7, 4, 0, 4, 8, 2, 9, 8, 4, 8]
Explanation : 4 is swapped by 8 at each occurrence.
Input : test_list = [4, 7, 8, 0, 8, 4], i, j = 4, 8
Output : [8, 7, 4, 0, 4, 8]
Explanation : 4 is swapped by 8 at each occurrence.
方法一:使用循环+条件语句
在此,我们使用条件 if-else 语句执行切换任务,并使用循环执行迭代任务。
Python3
# Python3 code to demonstrate working of
# Toggle i,j elements in List
# Using loop + conditional statements
# initializing list
test_list = [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
for idx in range(len(test_list)):
# perform toggling
if int(test_list[idx]) == i:
test_list[idx] = j
elif int(test_list[idx]) == j:
test_list[idx] = i
# printing result
print("The altered list : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Toggle i,j elements in List
# Using list comprehension + external function
# external toggle
def toggle(ele, i, j):
# performing toggle
if ele == i:
return j
elif ele == j:
return i
return ele
# initializing list
test_list = [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# list comprehension for 1 liner
res = [toggle(ele, i, j) for ele in test_list]
# printing result
print("The altered list : " + str(res))
输出:
The original list is : [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4]
The altered list : [8, 7, 4, 0, 4, 8, 2, 9, 8, 4, 8]
方法二:使用列表推导+外部函数
在此,我们使用外部切换函数执行切换任务,并使用列表理解来遍历列表。
蟒蛇3
# Python3 code to demonstrate working of
# Toggle i,j elements in List
# Using list comprehension + external function
# external toggle
def toggle(ele, i, j):
# performing toggle
if ele == i:
return j
elif ele == j:
return i
return ele
# initializing list
test_list = [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4]
# printing original list
print("The original list is : " + str(test_list))
# initializing i, j
i, j = 4, 8
# list comprehension for 1 liner
res = [toggle(ele, i, j) for ele in test_list]
# printing result
print("The altered list : " + str(res))
输出:
The original list is : [4, 7, 8, 0, 8, 4, 2, 9, 4, 8, 4]
The altered list : [8, 7, 4, 0, 4, 8, 2, 9, 8, 4, 8]