Python – 字符串列表中的反向范围
给定一个字符串列表,将字符串列表的每个元素从第 i 个索引反转到第 j 个索引。
Input : test_list = [“Geeksforgeeks”, “Best”, “Geeks”], i, j = 1, 2
Output : [‘ee’, ‘es’, ‘ee’]
Explanation : Range of strings are extracted.
Input : test_list = [“Geeksforgeeks”], i, j = 1, 7
Output : [‘eeksfor’]
Explanation : Single string, from e to r (7 elements) are sliced.
方法 #1:使用循环 + reversed() +字符串切片
上述方法的组合可以用来解决这个问题。在此,我们使用使用切片提取的 reversed() 执行范围反转。
Python3
# Python3 code to demonstrate working of
# Common list elements and dictionary values
# Using set() and intersection()
# initializing list
test_list = ["Geeksforgeeks", "Best", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing range
i, j = 1, 3
res = []
for ele in test_list:
# slicing and appending range
res.append(ele[i : j + 1])
# printing result
print("Sliced strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Common list elements and dictionary values
# Using map() + slicing + lambda
# initializing list
test_list = ["Geeksforgeeks", "Best", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing range
i, j = 1, 3
# map used to extend logic to each string
res = list(map(lambda x : x[i : j + 1], test_list))
# printing result
print("Sliced strings : " + str(res))
输出
The original list : ['Geeksforgeeks', 'Best', 'Geeks']
Sliced strings : ['eek', 'est', 'eek']
方法 #2:使用 map() + 切片 + lambda
这是可以执行此任务的另一种方式。在此,我们使用 map() 将使用 lambda 制作的切片的逻辑扩展到整个列表。
Python3
# Python3 code to demonstrate working of
# Common list elements and dictionary values
# Using map() + slicing + lambda
# initializing list
test_list = ["Geeksforgeeks", "Best", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing range
i, j = 1, 3
# map used to extend logic to each string
res = list(map(lambda x : x[i : j + 1], test_list))
# printing result
print("Sliced strings : " + str(res))
输出
The original list : ['Geeksforgeeks', 'Best', 'Geeks']
Sliced strings : ['eek', 'est', 'eek']