📜  Python – 根据第 K 个字符追加

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

Python – 根据第 K 个字符追加

给定一个字符串列表,根据第 K 个索引值附加到字符串 i 或 j 值。

方法#1:使用循环

这是解决这个问题的蛮力方法,我们检查每个字符串的第 K 个索引,如果发现是 N,则附加 i 值,否则附加 j。

Python3
# Python3 code to demonstrate working of 
# Append according to Kth character
# Using loop
  
# initializing lists
test_list = ["geeksforgeeks", "best", "for", "geeks"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing K
K = 2 
  
# initializing N 
N = 'e'
  
# initializing i, j 
i, j = "**", "##"
  
res = []
for sub in test_list:
      
    # checking for Kth index to be N
    if sub[K] == N:
        res.append(sub + i)
    else :
        res.append(sub + j)
  
# printing results 
print("The resultant List : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Append according to Kth character
# Using list comprehension
  
# initializing lists
test_list = ["geeksforgeeks", "best", "for", "geeks"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing K
K = 2 
  
# initializing N 
N = 'e'
  
# initializing i, j 
i, j = "**", "##"
  
# shorthand to solve this problem
res = [sub + i if sub[K] == N else sub + j for sub in test_list]
  
# printing results 
print("The resultant List : " + str(res))


输出
The original list : ['geeksforgeeks', 'best', 'for', 'geeks']
The resultant List : ['geeksforgeeks**', 'best##', 'for##', 'geeks**']

方法#2:使用列表推导

这以类似的方式解决了这个问题,只是不同的是,它是一种速记,可以用作解决这个问题的一种线性方法。

Python3

# Python3 code to demonstrate working of 
# Append according to Kth character
# Using list comprehension
  
# initializing lists
test_list = ["geeksforgeeks", "best", "for", "geeks"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing K
K = 2 
  
# initializing N 
N = 'e'
  
# initializing i, j 
i, j = "**", "##"
  
# shorthand to solve this problem
res = [sub + i if sub[K] == N else sub + j for sub in test_list]
  
# printing results 
print("The resultant List : " + str(res))
输出
The original list : ['geeksforgeeks', 'best', 'for', 'geeks']
The resultant List : ['geeksforgeeks**', 'best##', 'for##', 'geeks**']