Python程序打印列表中元素重复出现的字符串
给定一个字符串列表,编写一个Python程序,提取列表元素中特定值(此处使用 K 描述)出现多次的所有字符串。
例子:
Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘e’
Output : [‘geeksforgeeks’, ‘geeks’]
Explanation : geeks and geeksforgeeks have 2 and 4 occurrences of K respectively.
.
Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = ‘k’
Output : [‘geeksforgeeks’]
Explanation : geeksforgeeks has 2 occurrences of K
方法 1:使用循环和count()
在这里,我们使用计数检查每个字符串中 K 的所有出现,并检查是否有任何字符串的 K 出现次数超过 1 次,如果找到,则提取该字符串。
Python3
# initializing Matrix
test_list = ["geeksforgeeks", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
res = []
for ele in test_list:
# checking for count greater than 1 (repetitive)
if ele.count(K) > 1:
res.append(ele)
# printing result
print("Repeated K strings : " + str(res))
Python3
# initializing Matrix
test_list = ["geeksforgeeks", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
# checking for count greater than 1 (repetitive)
# one-liner using list comprehension
res = [ele for ele in test_list if ele.count(K) > 1]
# printing result
print("Repeated K strings : " + str(res))
输出:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]
方法 2:使用列表推导和count()
这是此任务的简写解决方案,类似于上述方法,只是使用列表理解来完成迭代使用。
蟒蛇3
# initializing Matrix
test_list = ["geeksforgeeks", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
# checking for count greater than 1 (repetitive)
# one-liner using list comprehension
res = [ele for ele in test_list if ele.count(K) > 1]
# printing result
print("Repeated K strings : " + str(res))
输出:
The original list is : [‘geeksforgeeks’, ‘best’, ‘for’, ‘geeks’]
Repeated K strings : [‘geeksforgeeks’, ‘geeks’]