3 回答

TA貢獻1835條經驗 獲得超7個贊
您的功能已關閉,因為您正在將列表索引與您嘗試匹配的值進行比較i == x
。您想使用myList[i] == x
. 但似乎您實際上想檢查長度,所以len(myList[i]) == x
.
但是,我更喜歡迭代循環中的實際元素(或 Joran Beasley 在評論中指出的列表理解)。您還提到您想檢查是否為特定長度的字符串,因此您還可以添加對對象類型的檢查:
def listNum(myList, x): return [item for item in myList if type(item) is str and len(item) == x]

TA貢獻1817條經驗 獲得超6個贊
使用setdefault()方法。此解決方案應該為您提供映射到各自單詞的所有單詞長度的字典
代碼
myList = ["Hello", "How","are", "you"]
dict1 = {}
for ele in myList:
key = len(ele)
dict1.setdefault(key, [])
dict1[key].append(ele)
輸出
我想這是您想要實現的輸出。
>>> print(dict1)
{5: ['Hello'], 3: ['How', 'are', 'you']}
您可以使用它來查詢字典并獲取與其字長相對應的單詞。例如dict1[5]會返回'hello'

TA貢獻1804條經驗 獲得超7個贊
試試這個代碼。
代碼
def func_same_length(array,index):
res = [array[i] for i in range(0,len(array)) if len(array[index]) == len(array[i]) and i!=index]
return res
myList = ["Hello", "How", "are", "you"]
resSet = set()
for index in range(0,len(myList)):
res = func_same_length(myList,index)
for i in res:
resSet.add(i)
print(resSet)
輸出
{'How', 'are', 'you'}
添加回答
舉報