簡體   English   中英

初學者 Python 問題:將列表對象轉換為整數時遇到問題

[英]Beginner Python question: trouble converting list objects to integers

此代碼導致

TypeError: 'list' object cannot be interpreted as an integer.

在添加用戶輸入之前它正在工作。 該代碼返回數字與輸入數字對的范圍重疊的次數。 提前致謝!

user_input_1 = input("Enter the first pair here: ")
lst1 = [int(i) for i in user_input_1.split(" ") if i.isdigit()]

user_input_2 = input("Enter the second pair here: ")
lst2 = [int(i) for i in user_input_2.split(" ") if i.isdigit()]

user_input_3 = input("Enter the third pair here: ")
lst3 = [int(i) for i in user_input_3.split(" ") if i.isdigit()]

user_input_4 = input("Choose a center number: ")
number = int(user_input_4)


mainlist = [[lst2], [lst2], [lst3]]

def count_overlapping(mainlist, number): 
    count = 0
    for element in mainlist:
        if number in range(element[0], element[-1]) or number == element[0] or number == element[-1]:
            count += 1
    return count    

print(count_overlapping(mainlist, number))

你有一個額外級別的列表,你不需要,所以當你認為你得到一個 int 值時,你仍然得到一個列表。

mainlist = [[lst2], [lst2], [lst3]]更改為mainlist = [lst2, lst2, lst3]

mainlst = [[lst1], [lst2], [lst3]]
[[[1, 2, 3, 4, 5, 6, 7, 8, 9]],
 [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]],
 [[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]]

mainlst = [lst1, lst2, lst3]                                                                                     
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]

mainlist是列表列表的列表,您應該使用:

mainlist = [lst2, lst2, lst3]

此外,您可以改進您的 function count_overlapping (假設您的輸入有成對的數字/2 個數字):

def count_overlapping(mainlist, number):
    return sum(1 for [a, b] in mainlist if number >= a and number <= b)

暫無
暫無

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

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