簡體   English   中英

無法迭代python中的列表

[英]Not able to iterate over a list in python

嗨,我無法將由“空格”分隔的字符串轉換為 for 循環中的列表。 顯示運行時錯誤:AttributeError: 'NoneType' object has no attribute 'sorted'

#The code is to get the second highest number

n = int(input())
arr = map(int, input().split())   # this is a string
arr_list = []
for i in range(n):
    arr_list = arr_list.append(arr)
    arr_list = arr_list.sorted()
    arr_set = set(arr_list)
    if len(arr_list) > 1:
        print(list(arr_set)[-2])
    else:
        print(arr_list[0])

arr_list.append(arr)arr附加到arr_list並返回None ,因此:

arr_list = arr_list.append(arr) ==> arr_list = None

arr_list.sorted() => None.sorted() ==> AttributeError: 'NoneType' object has no attribute 'sorted'

此外,要使用sorted(list)對列表進行sorted ,請使用sorted(list)而不是list.sorted()

要將字符串轉換為列表,您應該執行以下操作:

arr = list(map(int, input().split())) # this is a list

您有許多錯誤,但可以簡化為:

arr = sorted(set(map(int, input('Enter space-separated numbers: ').split())))
if len(arr) > 1:
    print(arr[-2])
else:
    print(arr[0])

map()返回一個地圖對象。 set通過迭代地圖創建唯一值。 sorted()將它們按順序排列。

您代碼中的原始錯誤是:

arr_list = arr_list.append(arr)
arr_list = arr_list.sorted()

arr_list.append()是一個就地操作並返回None ,然后將其分配給arr_list None沒有.sorted()方法。

暫無
暫無

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

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