Python – 根据第 K 个字符追加
给定一个字符串列表,根据第 K 个索引值附加到字符串 i 或 j 值。
Input : test_list = [“geeksforgeeks”, “best”, “for”, “geeks”], K = 2, N = ‘e’, i, j = “@@”, “..”
Output : [‘geeksforgeeks..’, ‘best@@’, ‘for@@’, ‘geeks..’]
Explanation : geeksforgeeks and geeks having similar 2nd occ. value as ‘e’, hence gets appended by “..”.
Input : test_list = [“giiksforgeeks”, “bst”, “for”, “geeks”], K = 2, N = ‘e’, i, j = “@@”, “..”
Output : [‘giiksforgeeks@@’, ‘best@@’, ‘for@@’, ‘geeks@@’]
Explanation : No values with K value ‘e’, all appended by @@.
方法#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**']