Python – 用 K 代替第一次出现的元素
有时,在处理Python数据时,我们可能会遇到一个问题,即我们需要对列表中每个元素的第一次出现执行替换。这类问题可以应用于各种领域,例如 Web 开发。让我们讨论可以执行此任务的某些方式。
Input : test_list = [4, 3, 3], K = 10
Output : [10, 10, 3]
Input : test_list = [4, 3, 7], K = 8
Output : [8, 8, 8]
方法#1:使用循环
这是解决这个问题的粗暴方法。在此,我们为列表中的每个元素运行一个循环并存储已发生的元素以供查找,并相应地分配 K。
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using loop
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using loop
lookp = set()
res = []
for ele in test_list:
if ele not in lookp:
lookp.add(ele)
res.append(K)
else:
res.append(ele)
# printing result
print("List after Substitution : " + str(res))
输出 :
The original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]
方法 #2:使用defaultdict() + next()
+ count + 列表理解
上述功能的组合提供了解决这个问题的简写。在此,我们使用 count 执行检查第一次出现的任务,如果元素第一次出现,则 next() 返回,并创建布尔列表,其中第一次出现的为 1,重复的为 0。使用列表推导将这些转换为所需的结果。
# Python3 code to demonstrate working of
# Substitute K for first occurrence of elements
# Using defaultdict() + next() + count + list comprehension
from itertools import count
from collections import defaultdict
# initializing list
test_list = [4, 3, 3, 7, 8, 7, 4, 6, 3]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 10
# Substitute K for first occurrence of elements
# Using defaultdict() + next() + count + list comprehension
freq = defaultdict(count)
temp = [int(next(freq[val]) == 0) for val in test_list]
res = [K if ele else test_list[idx] for idx, ele in enumerate(temp)]
# printing result
print("List after Substitution : " + str(res))
输出 :
The original list is : [4, 3, 3, 7, 8, 7, 4, 6, 3]
List after Substitution : [10, 10, 3, 10, 10, 7, 4, 10, 3]