📌  相关文章
📜  Python - 匹配列表元素中的第 K 个数字

📅  最后修改于: 2022-05-13 01:55:02.079000             🧑  作者: Mango

Python - 匹配列表元素中的第 K 个数字

有时我们可能会遇到一个问题,如果它包含在第 K 索引处具有相同数字的数字,我们需要查找一个列表。这个特殊的实用程序在日常编程中有一个应用程序。让我们讨论一些可以实现此任务的方法。

方法 #1:使用列表理解 + map()
我们可以通过将元素转换为字符串然后测试字符串的第 K 个元素来解决这个问题,如果它们相等,我们可以返回 true,然后转换为 set 并测试结果的大小是否为 1。转换由 map 完成,set函数转换为 set 和 list 理解检查字符串的第 K 个元素。

# Python3 code to demonstrate
# Kth Number digit match
# using list comprehension + map()
  
# initializing list 
test_list = [467, 565, 2645, 8668]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 1
  
# using list comprehension + map()
# Kth Number digit match
res = len(set(sub[K] for sub in map(str, test_list))) == 1
  
# print result
print("Does each element of index K have same digit ? " + str(res))
输出 :
The original list : [467, 565, 2645, 8668]
Does each element of index K have same digit ? True

方法 #2:使用all() + 列表推导
这是可以解决此问题的另一种方法。在此,我们使用 all函数检查所有元素并返回布尔结果,列表解析执行 str函数转换字符串的部分,并检查具有第 K 个元素的第 K 位的所有元素。

# Python3 code to demonstrate
# Kth Number digit match
# using list comprehension + all()
  
# initializing list 
test_list = [467, 565, 2645, 8668]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 1
  
# using list comprehension + all()
# Kth Number digit match
res = all(str(i)[K] == str(test_list[K])[K] for i in test_list)
  
# print result
print("Does each element of index K have same digit ? " + str(res))
输出 :
The original list : [467, 565, 2645, 8668]
Does each element of index K have same digit ? True