从列表的每个元素中删除特定数字的Python程序
给定元素列表,这里的任务是编写一个Python程序,该程序可以从每个元素中删除所有特定数字的存在,然后返回结果列表。
例子:
Input : test_list = [333, 893, 1948, 34, 2346], K = 3
Output : [”, 89, 1948, 4, 246]
Explanation : All occurrences of 3 are removed.
Input : test_list = [345, 893, 1948, 34, 2346], K = 5
Output : [34, 893, 1948, 34, 2346]
Explanation : All occurrences of 5 are removed.
方法 1:使用循环、str() 和 join()
在这种情况下,我们通过将元素转换为字符串并检查每个数字并在加入时忽略以获取新元素来执行重组元素的任务。最后使用 int() 将每个元素转换为整数。
例子:
Python3
# initializing list
test_list = [345, 893, 1948, 34, 2346]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = []
for ele in test_list:
# joining using join(),
if list(set(str(ele)))[0] == str(K) and len(set(str(ele))) == 1:
res.append('')
else:
res.append(int(''.join([el for el in str(ele) if int(el) != K])))
# printing result
print("Modified List : " + str(res))
Python3
# initializing list
test_list = [345, 893, 1948, 34, 2346]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# list comprehension performing task as one liner
res = ['' if list(set(str(ele)))[0] == str(K) and len(set(str(ele))) == 1 else int(
''.join([el for el in str(ele) if int(el) != K])) for ele in test_list]
# printing result
print("Modified List : " + str(res))
输出:
The original list is : [345, 893, 1948, 34, 2346]
Modified List : [45, 89, 1948, 4, 246]
方法 2:使用列表推导式、int()、str() 和 join()
与上述方法类似,连接使用 join() 完成,相互转换使用 int() 和 str() 执行。
例子:
蟒蛇3
# initializing list
test_list = [345, 893, 1948, 34, 2346]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# list comprehension performing task as one liner
res = ['' if list(set(str(ele)))[0] == str(K) and len(set(str(ele))) == 1 else int(
''.join([el for el in str(ele) if int(el) != K])) for ele in test_list]
# printing result
print("Modified List : " + str(res))
输出:
The original list is : [345, 893, 1948, 34, 2346]
Modified List : [45, 89, 1948, 4, 246]