[英]How to iterate a list with string elements and append a specific value to another list if a specific conditional statement in the first list is true?
我在谷歌 Colab 工作。 我有一個名為dir
的列表,其中包含字符串元素。 我想創建一個新列表,我將在其中 append 一個特定的數字,具體取決於是否在dir
列表的元素中找到特定的字符序列。
這是我寫的代碼:
labels=[]
for value in dir:
if '/River/' in dir:
labels.append(1)
elif '/HerbaceousVegetation/' in dir:
labels.append(2)
elif '/Highway/' in dir:
labels.append(3)
elif '/Residential/' in dir:
labels.append(4)
elif '/Industrial/' in dir:
labels.append(5)
elif '/AnnualCrop/' in dir:
labels.append(6)
elif '/Pasture/' in dir:
labels.append(7)
elif '/PermanentCrop/' in dir:
labels.append(8)
elif '/SeaLake/' in dir:
labels.append(9)
else:
labels.append(10)
結果是每個元素中具有值 10 的列表labels
。 似乎條件語句只考慮了else
語句。 如何轉換我的代碼以考慮所有語句?
這里的問題是您要檢查的是 list dir
中的字符串而不是 list dir
的元素中的字符串。 將 if 語句更改為(el)if 'your_string' in value:
它將按您的預期工作。
dir
已經引用了內置的 function dir()
並且不應用作變量。
您正在檢查列表中是否存在某個字符串,而您應該檢查該字符串是否存在於列表的元素中。
labels = []
l = [] #should be filled with your data replacing dir
for value in l:
if '/River/' in value:
labels.append(1)
elif '/HerbaceousVegetation/' in value:
labels.append(2)
#all your cases
else:
labels.append(10)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.