亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

類型錯誤:類型“分數”的對象沒有 len()

類型錯誤:類型“分數”的對象沒有 len()

米脂 2022-08-16 18:52:45
我已經調整了它以將自我添加到更新中,但現在我在測試東西的主要內容中遇到了麻煩。from file import Fractionimport randomdef main():    a = Fraction()    b = a.update()main()我試圖使這個for循環工作,它應該將列表的第一個數字減去第二個,第二個數字減去第三個數字,依此類推,然后使用這些值創建一個新列表。該部分工作,但更新功能是我遇到麻煩的地方。__init__class Fraction():    def __init__(self):        shape = int(input("How many sides does the shape have? : "))        if shape <= 0: #doesnt work with negatives?            print("Please make a valid choice (positive integers only)")            shape = int(input("How many sides does the shape have? : "))        numbers = 0        print("Your numbers are: ")        numbers = []        for i in range(0,shape):            n = random.randint(1,100)            numbers.append(n)        print(numbers)    def update(numbers):        long=len(numbers)        for i in range(long):            newnum = numbers[i]-numbers[i+1]        print(newnum)
查看完整描述

1 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

您必須 使用 才能訪問 中的數字。你應該使用而不是在self.numberupdateselfnumberdef update(number)


此外,要創建新列表,您必須在 -loop 之前創建空列表并創建到此列表。稍后,您可以將此列表獲取為forappend(newnum)returnb = ...


class Fraction():


    def __init__(self):

        shape = int(input("How many sides does the shape have? : "))


        if shape <= 0: #doesnt work with negatives?

            print("Please make a valid choice (positive integers only)")

            shape = int(input("How many sides does the shape have? : "))


        self.numbers = []

        for i in range(shape):

            n = random.randint(1, 100)

            self.numbers.append(n)

        print("Your numbers are:", self.numbers)


    def update(self):

        newlist = []


        long = len(self.numbers)

        for i in range(long-1): # it has to be long-1 because later `long-1+1`will give `long` 

            newnum = self.numbers[i] - self.numbers[i+1]

            newlist.append(newnum)


        return newlist


import random


def main():

    a = Fraction()

    b = a.update()

    print(b)

main()

順便說一句:最好使用外部類并運行它,以便它可以使用來自或文件或硬編碼的變量運行。使用相同的值一次又一次地測試代碼是有幫助的。input()Fraction(shape)input()


查看完整回答
反對 回復 2022-08-16
  • 1 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號