簡體   English   中英

根據列表中變量的長度查找列表中的索引項

[英]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或其他值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM