Python – 检查第 K 个索引元素是否唯一
给定一个字符串列表,检查是否所有第 K 个索引元素都是唯一的。
Input : test_list = [“gfg”, “best”, “for”, “geeks”], K = 1
Output : False
Explanation : e occurs as 1st index in both best and geeks.
Input : test_list = [“gfg”, “best”, “geeks”], K = 2
Output : True
Explanation : g, s, e, all are unique.
方法#1:使用循环
这是解决这个问题的粗暴方法。在此,我们对每个字符串进行迭代,并在重复任何元素时标记关闭,并返回 false。
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# Using loop
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = []
flag = True
for ele in test_list:
# checking if element is repeated
if ele[K] in res:
flag = False
break
else:
res.append(ele[K])
# printing result
print("Is Kth index all unique : " + str(flag))
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# Using Counter() + all()
from collections import Counter
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# getting count of each Kth index item
count = Counter(sub[K] for sub in test_list)
# extracting result
res = all(val < 2 for val in count.values())
# printing result
print("Is Kth index all unique : " + str(res))
输出
The original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
方法 #2:使用 Counter() + all()
在此,我们计算每个字符的频率。在第 K 个索引处,all() 用于检查 Counter 是否小于 2。
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# Using Counter() + all()
from collections import Counter
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# getting count of each Kth index item
count = Counter(sub[K] for sub in test_list)
# extracting result
res = all(val < 2 for val in count.values())
# printing result
print("Is Kth index all unique : " + str(res))
输出
The original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True