📌  相关文章
📜  打印列表元素指定索引处常见元素的Python程序

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

打印列表元素指定索引处常见元素的Python程序

给定一个字符串列表,任务是编写一个Python程序来提取列表中每个元素的指定索引处相同的所有字符。

方法 1:使用min() len()循环

在这种情况下,最初提取最小长度字符串以检查索引以进行迭代以确保字符串中的所有索引。然后使用循环检查每个索引的相似字符,如果找到,则将字符附加到结果中。

Python3
# initializing Matrix
test_list = ["geeks", "weak", "beak", "peek"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting min length string
min_len = min(len(ele) for ele in test_list)
  
res = []
for idx in range(0, min_len):
    flag = True
    for ele in test_list:
  
        # checking for all equal columns
        if ele[idx] != test_list[0][idx]:
            flag = False
            break
  
    if flag:
        res.append(test_list[0][idx])
  
  
# printing result
print("Extracted similar characters : " + str(res))


Python3
# initializing Matrix
test_list = ["geeks", "weak", "beak", "peek"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting min length string
min_len = min(len(ele) for ele in test_list)
  
res = []
for idx in range(0, min_len):
  
    # using all() for condition injection
    if all(ele[idx] == test_list[0][idx] for ele in test_list):
        res.append(test_list[0][idx])
  
# printing result
print("Extracted similar characters : " + str(res))


输出:

方法 2:使用all() min() len()循环

在这里,我们使用 all() 执行检查所有元素是否匹配的任务,减少嵌套循环,提高可读性。

蟒蛇3

# initializing Matrix
test_list = ["geeks", "weak", "beak", "peek"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting min length string
min_len = min(len(ele) for ele in test_list)
  
res = []
for idx in range(0, min_len):
  
    # using all() for condition injection
    if all(ele[idx] == test_list[0][idx] for ele in test_list):
        res.append(test_list[0][idx])
  
# printing result
print("Extracted similar characters : " + str(res))

输出: