根据列表中变量的长度在列表中查找索引项

Find index item in a list based on the length of a variable in the list

我有两个列表:

list_one = ['I', 'walk','on','the','street','','','','']
list_two = ['','','','','','with','my','pajamas','on']

对于这两个列表,我的目标是不同的。对于 list_one 我想找到长度大于 0 的最后一项。对于 list_two 我想找到长度大于 0 的第一个变量的索引。

现在我创建了两个函数:

def index_last_long(sentence):
  for index, word in enumerate(sentence):
    if len(word) == 0:
      return index-1

def index_first_long(sentence):
  for index, word in enumerate(sentence):
    if len(word) > 0:
      return index

这确实有效。但是,我认为必须有其他方法需要更少的代码来执行相同的任务。

谁知道这样的方法?

你可以这样做:

last = next((i for i, x in enumerate(reversed(list_one)) if len(x) > 0), None)
first = next((i for i, x in enumerate(list_two) if len(x) > 0), None)

如果这样的索引不存在,则返回None。随意修改该值,例如 -1 或其他内容。