📌  相关文章
📜  Python程序从字符串列表中查找第K个单词的字符位置

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

Python程序从字符串列表中查找第K个单词的字符位置

给定一个字符串列表。任务是找到单词的字符位置索引,它位于字符串列表中的第 K 个索引处。

例子:

方法 #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))


输出

方法 #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))
输出