Python程序从字符串列表中查找第K个单词的字符位置
给定一个字符串列表。任务是找到单词的字符位置索引,它位于字符串列表中的第 K 个索引处。
例子:
Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 21
Output : 0
Explanation : 21st index occurs in “geeks” and point to “g” which is 0th element of word.
Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 15
Output : 1
Explanation : 15th index occurs in “best” and point to “e” which is 1st element of word.
方法 #1:使用 enumerate() + 列表理解
在此,我们使用嵌套的 enumerate() 来检查列表中的单词和字符串的索引,列表推导用于将逻辑封装在 1 行中。
Python3
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using enumerate() + list comprehension
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# enumerate to get indices of all inner and outer list
res = [ele[0] for sub in enumerate(test_list) for ele in enumerate(sub[1])]
# getting index of word
res = res[K]
# printing result
print("Index of character at Kth position word : " + str(res))
Python3
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(
range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res))
The original list is : [‘geekforgeeks’, ‘is’, ‘best’, ‘for’, ‘geeks’]
Index of character at Kth position word : 2
方法 #2:使用 next() + zip() + count()
在此,我们使用 zip() 将单词数与其计数配对,并累积直到我们没有达到第 K 个索引。
Python3
# Python3 code to demonstrate working of
# Word Index for K position in Strings List
# Using next() + zip() + count()
from itertools import count
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 20
# count() for getting count
# pairing using zip()
cnt = count()
res = next(j for sub in test_list for j, idx in zip(
range(len(sub)), cnt) if idx == K)
# printing result
print("Index of character at Kth position word : " + str(res))
The original list is : [‘geekforgeeks’, ‘is’, ‘best’, ‘for’, ‘geeks’]
Index of character at Kth position word : 2